Capacitor with Angular
Angular-specific patterns and best practices for Capacitor app development — project structure, services, lifecycle hooks, NgZone integration, and plugin usage.
Prerequisites
- Capacitor 6, 7, or 8 app with Angular 16+.
- Node.js and npm installed.
- Angular CLI installed (
npm install -g @angular/cli). - For iOS: Xcode installed.
- For Android: Android Studio installed.
Agent Behavior
- Auto-detect before asking. Check the project for
angular.json,package.json,capacitor.config.tsorcapacitor.config.json, and existing directory structure. Only ask the user when something cannot be detected. - Guide step-by-step. Walk the user through the process one step at a time.
- Adapt to project style. Detect whether the project uses standalone components or NgModule-based architecture and adapt code examples accordingly.
Procedures
Step 1: Analyze the Project
Auto-detect the following by reading project files:
- Angular version: Read
@angular/coreversion frompackage.json. - Capacitor version: Read
@capacitor/coreversion frompackage.json. If not present, Capacitor has not been added yet — proceed to Step 2. - Architecture style: Check
src/main.tsforbootstrapApplication(standalone) vs.platformBrowserDynamic().bootstrapModule(NgModule). Checkangular.jsonfor further confirmation. - Platforms: Check which directories exist (
android/,ios/). - Capacitor config format: Check for
capacitor.config.ts(TypeScript) orcapacitor.config.json(JSON). - Build output directory: Read
outputPathfromangular.jsonunderprojects > <project-name> > architect > build > options > outputPath. This is needed for Capacitor'swebDirsetting.
Step 2: Add Capacitor to an Angular Project
Skip if @capacitor/core is already in package.json.
-
Install Capacitor core and CLI:
-
Initialize Capacitor:
When prompted, set the web directory to the Angular build output path detected in Step 1. For Angular 17+ with the application builder, this is typically
dist/<project-name>/browser. For older Angular versions, it is typicallydist/<project-name>. -
Verify the
webDirvalue in the generatedcapacitor.config.tsorcapacitor.config.jsonmatches the Angular build output path. If incorrect, update it:capacitor.config.ts:capacitor.config.json: -
Build the Angular app and add platforms:
Step 3: Project Structure
A Capacitor Angular project has this structure:
Key points:
- The
android/andios/directories contain native projects and should be committed to version control. - The
src/directory contains the Angular app, which is the web layer of the Capacitor app. - Capacitor plugins are called from Angular services or components inside
src/app/.
Step 4: Using Capacitor Plugins in Angular
Capacitor plugins are plain TypeScript APIs. Import and call them directly in Angular components or services.
Direct Usage in a Component
Wrapping Plugins in Angular Services (Recommended)
Wrapping Capacitor plugins in Angular services provides dependency injection, testability, and a single place to handle platform differences:
Use the service in a component:
Step 5: NgZone Integration for Plugin Event Listeners
Capacitor plugin event listeners run outside Angular's NgZone execution context. When a plugin listener updates component state, Angular's change detection does not automatically trigger. Wrap the handler logic in NgZone.run() to fix this.
Without NgZone (broken — UI does not update):
With NgZone (correct — UI updates properly):
Rule: Always use NgZone.run() inside Capacitor plugin event listener callbacks that update component or service state bound to templates.
Step 6: Lifecycle Hook Patterns
Use Angular lifecycle hooks to manage Capacitor plugin listeners. Register listeners in ngOnInit and remove them in ngOnDestroy to prevent memory leaks.
Service-Based Listener Management
For app-wide listeners (e.g., network status, app state), use a service initialized at app startup:
Initialize the service at app startup to ensure it runs immediately. In standalone apps, use APP_INITIALIZER or inject it in the root component. In NgModule apps, inject it in AppComponent:
Standalone (app.config.ts):
NgModule (app.component.ts):
Step 7: Platform Detection
Use Capacitor.isNativePlatform() and Capacitor.getPlatform() to conditionally run native-only code:
Use it in components to show/hide native-only features:
Step 8: Deep Link Routing
Handle deep links by mapping Capacitor's App.addListener('appUrlOpen', ...) event to Angular Router navigation:
Initialize DeepLinkService at app startup (same pattern as Step 6 — via APP_INITIALIZER or root component injection).
Step 9: Back Button Handling (Android)
Handle the Android hardware back button using App.addListener('backButton', ...):
Step 10: Build and Sync Workflow
After making changes to the Angular app, build and sync to native platforms:
To run on a device or emulator:
To open the native IDE for advanced configuration or debugging:
For live reload during development:
This starts ng serve internally and configures the native app to load from the development server.
Error Handling
- UI not updating from plugin listeners: Wrap the listener callback body in
NgZone.run(() => { ... }). This is the most common Angular-specific issue with Capacitor. webDirmismatch: Ifnpx cap synccopies the wrong files, verify thatwebDirincapacitor.config.tsorcapacitor.config.jsonmatches the Angular build output path. For Angular 17+ with the application builder, the path isdist/<project-name>/browser. For older Angular versions, it isdist/<project-name>.- Plugin not found at runtime: Run
npx cap syncafter installing any new plugin. Verify the plugin appears inpackage.jsondependencies. - Memory leaks from listeners: Always remove plugin listeners in
ngOnDestroy. Store thePluginListenerHandlereturned byaddListenerand callhandle.remove()on destroy. - Deep links not working: Verify the app URL scheme / universal links are configured in the native projects (
android/app/src/main/AndroidManifest.xmlfor Android,ios/App/App/Info.plistand associated domain entitlement for iOS). VerifyDeepLinkServiceis initialized at app startup. - Back button closes app unexpectedly: Ensure the back button listener checks
canGoBackbefore callingApp.exitApp(). Only exit when there is no navigation history. - Build output empty after
ng build: Verify theoutputPathinangular.jsonis correct. For Angular 17+, the default changed todist/<project-name>/browserwith the application builder.
Related Skills
capacitor-app-creation— Create a new Capacitor app from scratch.capacitor-app-development— General Capacitor development guidance not specific to Angular.capacitor-plugins— Install and configure Capacitor plugins from official and community sources.capacitor-react— React-specific patterns and best practices for Capacitor app development.ionic-angular— Ionic Framework with Angular (UI components, navigation, theming on top of Capacitor).capacitor-app-upgrades— Upgrade a Capacitor app to a newer major version.


