Basic information
About angular-best-practices
Angular performance optimization and best practices guide. Use when writing, reviewing, or refactoring Angular code for optimal performance, bundle size, and rendering efficiency.
angular-best-practices is an agent skill listed in the AddMCP.net directory, published by sickn33. Runtime: Python. License: MIT. The repository has 48,950 GitHub stars. Source code is hosted on github.com. Related topics: agent-skills, agentic-skills, ai-agent-skills, ai-agents, ai-coding.
Overview
What is angular-best-practices?
name: angular-best-practices description: "Angular performance optimization and best practices guide. Use when writing, reviewing, or refactoring Angular code for optimal performance, bundle size, and rendering efficiency." risk: safe source: self date_added: "2026-02-27"
Angular Best Practices
Comprehensive performance optimization guide for Angular applications. Contains prioritized rules for eliminating performance bottlenecks, optimizing bundles, and improving rendering.
When to Apply
Reference these guidelines when:
- Writing new Angular components or pages
- Implementing data fetching patterns
- Reviewing code for performance issues
- Refactoring existing Angular code
- Optimizing bundle size or load times
- Configuring SSR/hydration
Rule Categories by Priority
| Priority | Category | Impact | Focus | | -------- | --------------------- | ---------- | ------------------------------- | | 1 | Change Detection | CRITICAL | Signals, OnPush, Zoneless | | 2 | Async Waterfalls | CRITICAL | RxJS patterns, SSR preloading | | 3 | Bundle Optimization | CRITICAL | Lazy loading, tree shaking | | 4 | Rendering Performance | HIGH | @defer, trackBy, virtualization | | 5 | Server-Side Rendering | HIGH | Hydration, prerendering | | 6 | Template Optimization | MEDIUM | Control flow, pipes | | 7 | State Management | MEDIUM | Signal patterns, selectors | | 8 | Memory Management | LOW-MEDIUM | Cleanup, subscriptions |
1. Change Detection (CRITICAL)
{{ title() }}
Count: {{ count() }}
`, }) export class DashboardComponent { title = signal("Dashboard"); count = signal(0); } // WRONG - Mutable properties require zone.js checks @Component({ template: `{{ title }}
Count: {{ count }}
`, }) export class DashboardComponent { title = "Dashboard"; count = 0; } ``` ### Enable Zoneless for New Projects ```typescript // main.ts - Zoneless Angular (v20+) bootstrapApplication(AppComponent, { providers: [provideZonelessChangeDetection()], }); ``` **Benefits:** - No zone.js patches on async APIs - Smaller bundle (~15KB savings) - Clean stack traces for debugging - Better micro-frontend compatibility ---2. Async Operations & Waterfalls (CRITICAL)
Eliminate Sequential Data Fetching
// WRONG - Nested subscriptions create waterfalls
this.route.params.subscribe((params) => {
// 1. Wait for params
this.userService.getUser(params.id).subscribe((user) => {
// 2. Wait for user
this.postsService.getPosts(user.id).subscribe((posts) => {
// 3. Wait for posts
});
});
});
// CORRECT - Parallel execution with forkJoin
forkJoin({
user: this.userService.getUser(id),
posts: this.postsService.getPosts(id),
}).subscribe((data) => {
// Fetched in parallel
});
// CORRECT - Flatten dependent calls with switchMap
this.route.params
.pipe(
map((p) => p.id),
switchMap((id) => this.userService.getUser(id)),
)
.subscribe();
Avoid Client-Side Waterfalls in SSR
// CORRECT - Use resolvers or blocking hydration for critical data
export const route: Route = {
path: "profile/:id",
resolve: { data: profileResolver }, // Fetched on server before navigation
component: ProfileComponent,
};
// WRONG - Component fetches data on init
class ProfileComponent implements OnInit {
ngOnInit() {
// Starts ONLY after JS loads and component renders
this.http.get("/api/profile").subscribe();
}
}
3. Bundle Optimization (CRITICAL)
4. Rendering Performance (HIGH)
5. Server-Side Rendering (HIGH)
Configure Incremental Hydration
// app.config.ts
import {
provideClientHydration,
withIncrementalHydration,
} from "@angular/platform-browser";
export const appConfig: ApplicationConfig = {
providers: [
provideClientHydration(withIncrementalHydration(), withEventReplay()),
],
};
Defer Non-Critical Content
<!-- Critical above-the-fold content -->
<app-header />
<app-hero />
<!-- Below-fold deferred with hydration triggers -->
@defer (hydrate on viewport) {
<app-product-grid />
} @defer (hydrate on interaction) {
<app-chat-widget />
}
Use TransferState for SSR Data
@Injectable({ providedIn: "root" })
export class DataService {
private http = inject(HttpClient);
private transferState = inject(TransferState);
private platformId = inject(PLATFORM_ID);
getData(key: string): Observable<Data> {
const stateKey = makeStateKey<Data>(key);
if (isPlatformBrowser(this.platformId)) {
const cached = this.transferState.get(stateKey, null);
if (cached) {
this.transferState.remove(stateKey);
return of(cached);
}
}
return this.http.get<Data>(`/api/${key}`).pipe(
tap((data) => {
if (isPlatformServer(this.platformId)) {
this.transferState.set(stateKey, data);
}
}),
);
}
}
6. Template Optimization (MEDIUM)
No items
} {{ user.name }} Guest ``` ### Avoid Complex Template Expressions ```typescript // CORRECT - Precompute in component class Component { items = signal([]); sortedItems = computed(() => [...this.items()].sort((a, b) => a.name.localeCompare(b.name)) ); } // Template @for (item of sortedItems(); track item.id) { ... } // WRONG - Sorting in template every render @for (item of items() | sort:'name'; track item.id) { ... } ``` ---7. State Management (MEDIUM)
Use Selectors to Prevent Re-renders
// CORRECT - Selective subscription
@Component({
template: `<span>{{ userName() }}</span>`,
})
class HeaderComponent {
private store = inject(Store);
// Only re-renders when userName changes
userName = this.store.selectSignal(selectUserName);
}
// WRONG - Subscribing to entire state
@Component({
template: `<span>{{ state().user.name }}</span>`,
})
class HeaderComponent {
private store = inject(Store);
// Re-renders on ANY state change
state = toSignal(this.store);
}
Colocate State with Features
// CORRECT - Feature-scoped store
@Injectable() // NOT providedIn: 'root'
export class ProductStore { ... }
@Component({
providers: [ProductStore], // Scoped to component tree
})
export class ProductPageComponent {
store = inject(ProductStore);
}
// WRONG - Everything in global store
@Injectable({ providedIn: 'root' })
export class GlobalStore {
// Contains ALL app state - hard to tree-shake
}
8. Memory Management (LOW-MEDIUM)
Quick Reference Checklist
New Component
- [ ]
changeDetection: ChangeDetectionStrategy.OnPush - [ ]
standalone: true - [ ] Signals for state (
signal(),input(),output()) - [ ]
inject()for dependencies - [ ]
@forwithtrackexpression
Performance Review
- [ ] No methods in templates (use pipes or computed)
- [ ] Large lists virtualized
- [ ] Heavy components deferred
- [ ] Routes lazy-loaded
- [ ] Third-party libs dynamically imported
SSR Check
- [ ] Hydration configured
- [ ] Critical content renders first
- [ ] Non-critical content uses
@defer (hydrate on ...) - [ ] TransferState for server-fetched data
When to Use
This skill is applicable to execute the workflow or actions described in the overview.
Videos
Tutorials, guides, and showcases related to angular-best-practices. The player loads when you press play.
Videos belong to their creators. Relevance is approximate; check the channel and description before following setup steps.
Comments
No comments yet
Be the first to share feedback about this listing. Sign in to leave a comment.
Sign In