debug:angular
Debug Angular applications systematically with expert-level diagnostic techniques. This skill provides comprehensive guidance for troubleshooting dependency injection errors, change detection issues (NG0100), RxJS subscription leaks, lazy loading failures, zone.js problems, and common Angular runtime errors. Includes structured four-phase debugging methodology, Angular DevTools usage, console debugging utilities (ng.probe), and performance profiling strategies for modern Angular applications.
What this skill does
# Angular Debugging Guide
This guide provides a systematic approach to debugging Angular applications, covering common error patterns, debugging tools, and structured resolution phases.
## Common Error Patterns
### NullInjectorError
**Symptoms:**
- `NullInjectorError: No provider for <ServiceName>`
- `StaticInjectorError: No provider for <ServiceName>`
- Service injection fails at runtime
**Root Causes:**
1. Service not provided in any module or component
2. Circular dependency between services
3. Missing `@Injectable()` decorator
4. Service provided in wrong scope (lazy-loaded module vs root)
**Solutions:**
```typescript
// Solution 1: Provide in root (recommended for singletons)
@Injectable({
providedIn: 'root'
})
export class MyService { }
// Solution 2: Provide in specific module
@NgModule({
providers: [MyService]
})
export class FeatureModule { }
// Solution 3: Provide in component (new instance per component)
@Component({
providers: [MyService]
})
export class MyComponent { }
```
### ExpressionChangedAfterItHasBeenCheckedError (NG0100)
**Symptoms:**
- Error appears only in development mode
- Typically occurs in `ngAfterViewInit` or `ngAfterContentInit`
- Value changes during change detection cycle
**Root Causes:**
1. Modifying component state in lifecycle hooks after change detection
2. Child component modifying parent state
3. Async operations completing during change detection
**Solutions:**
```typescript
// Solution 1: Use setTimeout to defer change
ngAfterViewInit() {
setTimeout(() => {
this.value = 'new value';
});
}
// Solution 2: Use ChangeDetectorRef
constructor(private cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.value = 'new value';
this.cdr.detectChanges();
}
// Solution 3: Use async pipe (preferred for observables)
// In template: {{ value$ | async }}
value$ = this.service.getValue();
```
### Common NG Error Codes (NG0100-NG0999)
| Error Code | Description | Common Fix |
|------------|-------------|------------|
| NG0100 | Expression changed after checked | Use `detectChanges()` or `setTimeout` |
| NG0200 | Circular dependency in DI | Refactor service dependencies |
| NG0201 | No provider for service | Add to providers array or use `providedIn` |
| NG0300 | Multiple components match selector | Make selectors more specific |
| NG0301 | Export not found | Check export name in directive/component |
| NG0302 | Pipe not found | Import module containing pipe |
| NG0303 | No matching element | Check selector syntax |
| NG0500 | Hydration mismatch (SSR) | Ensure server/client render same content |
| NG0910 | Unsafe binding | Sanitize or use `bypassSecurityTrust*` |
| NG0912 | Component ID collision | Unique component selectors |
### RxJS Subscription Leaks
**Symptoms:**
- Memory leaks in long-running applications
- Console warnings about destroyed components
- Multiple HTTP requests for same data
- Performance degradation over time
**Detection:**
```typescript
// Use takeUntilDestroyed (Angular 16+)
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Component({...})
export class MyComponent {
private destroyRef = inject(DestroyRef);
ngOnInit() {
this.service.getData()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(data => this.data = data);
}
}
// Legacy approach with Subject
private destroy$ = new Subject<void>();
ngOnInit() {
this.service.getData()
.pipe(takeUntil(this.destroy$))
.subscribe();
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
```
**RxJS Debugging Operators:**
```typescript
import { tap } from 'rxjs/operators';
this.data$.pipe(
tap({
next: v => console.log('Value:', v),
error: e => console.error('Error:', e),
complete: () => console.log('Complete')
})
).subscribe();
```
### Lazy Loading Failures
**Symptoms:**
- `ChunkLoadError` in console
- Module fails to load on navigation
- Network errors for chunk files
**Common Causes:**
1. Incorrect path in `loadChildren`
2. Missing default export
3. Network/CDN issues
4. Cache issues after deployment
**Solutions:**
```typescript
// Correct lazy loading syntax (Angular 14+)
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module')
.then(m => m.FeatureModule)
},
// Standalone components (Angular 15+)
{
path: 'standalone',
loadComponent: () => import('./standalone/standalone.component')
.then(c => c.StandaloneComponent)
}
];
// Handle chunk load errors
// In app.component.ts or error handler
constructor(private router: Router) {
this.router.events.subscribe(event => {
if (event instanceof NavigationError) {
if (event.error.name === 'ChunkLoadError') {
window.location.reload();
}
}
});
}
```
### Zone.js Issues
**Symptoms:**
- Change detection not triggering
- UI not updating after async operations
- `runOutsideAngular` causing update issues
**Solutions:**
```typescript
constructor(private ngZone: NgZone) {}
// Force change detection inside Angular zone
ngOnInit() {
someExternalLibrary.onEvent((data) => {
this.ngZone.run(() => {
this.data = data;
});
});
}
// Optimize by running outside zone (for performance-critical code)
runHeavyComputation() {
this.ngZone.runOutsideAngular(() => {
// Heavy computation that doesn't need CD
const result = this.compute();
// Re-enter zone when updating UI
this.ngZone.run(() => {
this.result = result;
});
});
}
```
### Zoneless Angular (Angular 18+)
```typescript
// For zoneless applications, use signals
import { signal, computed, effect } from '@angular/core';
@Component({
selector: 'app-zoneless',
template: `<p>Count: {{ count() }}</p>`
})
export class ZonelessComponent {
count = signal(0);
doubled = computed(() => this.count() * 2);
increment() {
this.count.update(c => c + 1);
}
}
```
## Debugging Tools
### Angular DevTools
**Installation:**
- Chrome: Install from [Chrome Web Store](https://chrome.google.com/webstore/detail/angular-devtools)
- Firefox: Install from [Firefox Add-ons](https://addons.mozilla.org/firefox/addon/angular-devtools/)
**Features:**
1. **Component Explorer**: Inspect component tree, inputs, outputs, and state
2. **Profiler**: Record and analyze change detection cycles
3. **Dependency Injection Graph**: Visualize injector hierarchy
4. **Router Tree**: Debug routing configuration
**Requirements:**
- Application must be in development mode (`ng serve`)
- For deployed apps, build with `optimization: false`
### ng.probe() (Console Debugging)
```javascript
// In browser console
// Get component instance from DOM element
ng.getComponent($0);
// Get directive instances
ng.getDirectives($0);
// Get owning component
ng.getOwningComponent($0);
// Get injector
ng.getInjector($0);
// Trigger change detection
ng.applyChanges(component);
// Get context (for embedded views)
ng.getContext($0);
// Angular 14+ debugging utilities
const appRef = ng.getInjector(document.querySelector('app-root'))
.get(ng.coreTokens.ApplicationRef);
appRef.tick(); // Force global change detection
```
### Source Maps Configuration
```json
// angular.json
{
"projects": {
"my-app": {
"architect": {
"build": {
"configurations": {
"development": {
"sourceMap": true,
"optimization": false,
"extractLicenses": false,
"namedChunks": true
},
"production": {
"sourceMap": {
"scripts": true,
"styles": true,
"hidden": true,
"vendor": false
}
}
}
}
}
}
}
}
```
### Custom Error Handler
```typescript
// global-error-handler.ts
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable()
export class GlobaRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.