capacitor-angular
Guides the agent through Angular-specific patterns for Capacitor app development. Covers project structure, adding Capacitor to Angular projects, using Capacitor plugins in Angular services and components, NgZone integration for plugin event listeners, lifecycle hook patterns, dependency injection, routing with deep links, and environment-based platform detection. Do not use for creating a new Capacitor app from scratch, upgrading Capacitor versions, installing specific plugins, Ionic Framework setup, or non-Angular frameworks.
What this skill does
# Capacitor with Angular
Angular-specific patterns and best practices for Capacitor app development — project structure, services, lifecycle hooks, NgZone integration, and plugin usage.
## Prerequisites
1. **Capacitor 6, 7, or 8** app with Angular 16+.
2. Node.js and npm installed.
3. Angular CLI installed (`npm install -g @angular/cli`).
4. For iOS: Xcode installed.
5. For Android: Android Studio installed.
## Agent Behavior
- **Auto-detect before asking.** Check the project for `angular.json`, `package.json`, `capacitor.config.ts` or `capacitor.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:
1. **Angular version**: Read `@angular/core` version from `package.json`.
2. **Capacitor version**: Read `@capacitor/core` version from `package.json`. If not present, Capacitor has not been added yet — proceed to Step 2.
3. **Architecture style**: Check `src/main.ts` for `bootstrapApplication` (standalone) vs. `platformBrowserDynamic().bootstrapModule` (NgModule). Check `angular.json` for further confirmation.
4. **Platforms**: Check which directories exist (`android/`, `ios/`).
5. **Capacitor config format**: Check for `capacitor.config.ts` (TypeScript) or `capacitor.config.json` (JSON).
6. **Build output directory**: Read `outputPath` from `angular.json` under `projects > <project-name> > architect > build > options > outputPath`. This is needed for Capacitor's `webDir` setting.
### Step 2: Add Capacitor to an Angular Project
Skip if `@capacitor/core` is already in `package.json`.
1. Install Capacitor core and CLI:
```bash
npm install @capacitor/core
npm install -D @capacitor/cli
```
2. Initialize Capacitor:
```bash
npx cap init
```
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 typically `dist/<project-name>`.
3. Verify the `webDir` value in the generated `capacitor.config.ts` or `capacitor.config.json` matches the Angular build output path. If incorrect, update it:
**`capacitor.config.ts`:**
```typescript
import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'my-app',
webDir: 'dist/my-app/browser',
};
export default config;
```
**`capacitor.config.json`:**
```json
{
"appId": "com.example.app",
"appName": "my-app",
"webDir": "dist/my-app/browser"
}
```
4. Build the Angular app and add platforms:
```bash
ng build
npm install @capacitor/android @capacitor/ios
npx cap add android
npx cap add ios
npx cap sync
```
### Step 3: Project Structure
A Capacitor Angular project has this structure:
```
my-app/
├── android/ # Android native project
├── ios/ # iOS native project
├── src/
│ ├── app/
│ │ ├── app.component.ts
│ │ ├── app.config.ts # Standalone: app configuration
│ │ ├── app.module.ts # NgModule: root module
│ │ ├── app.routes.ts # Routing configuration
│ │ └── services/ # Angular services for Capacitor plugins
│ ├── environments/
│ │ ├── environment.ts
│ │ └── environment.prod.ts
│ ├── index.html
│ └── main.ts
├── angular.json
├── capacitor.config.ts # or capacitor.config.json
├── package.json
└── tsconfig.json
```
Key points:
- The `android/` and `ios/` 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
```typescript
import { Component } from '@angular/core';
import { Geolocation } from '@capacitor/geolocation';
@Component({
selector: 'app-location',
template: `
<div>
<p>Latitude: {{ latitude }}</p>
<p>Longitude: {{ longitude }}</p>
<button (click)="getCurrentPosition()">Get Location</button>
</div>
`,
standalone: true,
})
export class LocationComponent {
latitude: number | null = null;
longitude: number | null = null;
async getCurrentPosition() {
const position = await Geolocation.getCurrentPosition();
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
}
}
```
#### Wrapping Plugins in Angular Services (Recommended)
Wrapping Capacitor plugins in Angular services provides dependency injection, testability, and a single place to handle platform differences:
```typescript
import { Injectable } from '@angular/core';
import { Camera, CameraResultType, CameraSource, Photo } from '@capacitor/camera';
import { Capacitor } from '@capacitor/core';
@Injectable({
providedIn: 'root',
})
export class CameraService {
async takePhoto(): Promise<Photo> {
return Camera.getPhoto({
quality: 90,
allowEditing: false,
resultType: CameraResultType.Uri,
source: CameraSource.Camera,
});
}
async pickFromGallery(): Promise<Photo> {
return Camera.getPhoto({
quality: 90,
allowEditing: false,
resultType: CameraResultType.Uri,
source: CameraSource.Photos,
});
}
isNativePlatform(): boolean {
return Capacitor.isNativePlatform();
}
}
```
Use the service in a component:
```typescript
import { Component, inject } from '@angular/core';
import { CameraService } from '../services/camera.service';
@Component({
selector: 'app-photo',
template: `
<button (click)="takePhoto()">Take Photo</button>
<img *ngIf="photoUrl" [src]="photoUrl" alt="Captured photo" />
`,
standalone: true,
})
export class PhotoComponent {
private cameraService = inject(CameraService);
photoUrl: string | null = null;
async takePhoto() {
const photo = await this.cameraService.takePhoto();
this.photoUrl = photo.webPath ?? null;
}
}
```
### 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):**
```typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Network, ConnectionStatus } from '@capacitor/network';
import { PluginListenerHandle } from '@capacitor/core';
@Component({
selector: 'app-network',
template: `<p>Status: {{ networkStatus }}</p>`,
standalone: true,
})
export class NetworkComponent implements OnInit, OnDestroy {
networkStatus = 'Unknown';
private listenerHandle: PluginListenerHandle | null = null;
async ngOnInit() {
// BUG: This callback runs outside NgZone — the template will not update.
this.listenerHandle = await Network.addListener('networkStatusChange', (status) => {
this.networkStatus = status.connected ? 'Online' : 'Offline';
});
}
async ngOnDestroy() {
await this.listenerHandle?.remove();
}
}
```
**With NgZone (correct — UI updates properly):**
```typescript
import { Component, NgZone, OnInit, OnDestroy, inject } from '@angular/core';
import { Network, ConnectionStatus } from '@capacitor/network';
import { PluginListenerHandle } from '@capacitor/core';
@Component({
selector: 'appRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.