Skip to main content Home Creators beko2210 firstbrain angular-best-practices
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.
Jump to install Skills Marketplace Discover and explore AI skills built by the community.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
Copy promptShow prompt details A direct command skips the review prompt. Inspect the source before running it.
npx skills add https://github.com/BEKO2210/Firstbrain --skill angular-best-practicesThe command stays on one line. Scroll horizontally to inspect it before copying.
Prefer a local copy? Download the files currently available to SkillsMP.
Download Zip Downloading... 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. type skill created 2026-02-27T00:00:00.000Z domain software-development category frontend risk safe source self tags ["skill","software-development","frontend","angular"]
Angular Best Practices
Comprehensive performance optimization guide for Angular applications. Contains prioritized rules for eliminating performance bottlenecks, optimizing bundles, and improving rendering.
When to Use
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)
Use OnPush Change Detection
@Component ({
changeDetection : ChangeDetectionStrategy .OnPush ,
template : `<div>{{ count() }}</div>` ,
})
export class CounterComponent {
count = signal (0 );
}
({
: ,
})
{
count = ;
}
@Component
template
`<div>{{ count }}</div>`
export
class
CounterComponent
0
Prefer Signals Over Mutable Properties
@Component ({
template : `
<h1>{{ title() }}</h1>
<p>Count: {{ count() }}</p>
` ,
})
export class DashboardComponent {
title = signal ("Dashboard" );
count = signal (0 );
}
@Component ({
template : `
<h1>{{ title }}</h1>
<p>Count: {{ count }}</p>
` ,
})
export class DashboardComponent {
title = "Dashboard" ;
count = 0 ;
}
Enable Zoneless for New Projects
bootstrapApplication (AppComponent , {
providers : [provideZonelessChangeDetection ()],
});
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
this .route .params .subscribe ((params ) => {
this .userService .getUser (params.id ).subscribe ((user ) => {
this .postsService .getPosts (user.id ).subscribe ((posts ) => {
});
});
});
forkJoin ({
user : this .userService .getUser (id),
posts : this .postsService .getPosts (id),
}).subscribe ((data ) => {
});
this .route .params
.pipe (
map ((p ) => p.id ),
switchMap ((id ) => this .userService .getUser (id)),
)
.subscribe ();
Avoid Client-Side Waterfalls in SSR
export const route : Route = {
path : "profile/:id" ,
resolve : { data : profileResolver },
component : ProfileComponent ,
};
class ProfileComponent implements OnInit {
ngOnInit ( ) {
this .http .get ("/api/profile" ).subscribe ();
}
}
3. Bundle Optimization (CRITICAL)
Lazy Load Routes
export const routes : Routes = [
{
path : "admin" ,
loadChildren : () =>
import ("./admin/admin.routes" ).then ((m ) => m.ADMIN_ROUTES ),
},
{
path : "dashboard" ,
loadComponent : () =>
import ("./dashboard/dashboard.component" ).then (
(m ) => m.DashboardComponent ,
),
},
];
import { AdminModule } from "./admin/admin.module" ;
export const routes : Routes = [
{ path : "admin" , component : AdminComponent },
];
Use @defer for Heavy Components
@defer (on viewport) {
<app-analytics-chart [data ]="data()" />
} @placeholder {
<div class ="chart-skeleton" > </div >
}
<app-analytics-chart [data ]="data()" />
Avoid Barrel File Re-exports
import { Button , Modal , Table } from "@shared/components" ;
import { Button } from "@shared/components/button/button.component" ;
import { Modal } from "@shared/components/modal/modal.component" ;
Dynamic Import Third-Party Libraries
async loadChart ( ) {
const { Chart } = await import ('chart.js' );
this .chart = new Chart (this .canvas , config);
}
import { Chart } from 'chart.js' ;
4. Rendering Performance (HIGH)
Always Use trackBy with @for
@for (item of items(); track item.id) {
<app-item-card [item ]="item" />
}
@for (item of items(); track $index) {
<app-item-card [item ]="item" />
}
Use Virtual Scrolling for Large Lists import { CdkVirtualScrollViewport , CdkFixedSizeVirtualScroll } from '@angular/cdk/scrolling' ;
@Component ({
imports : [CdkVirtualScrollViewport , CdkFixedSizeVirtualScroll ],
template : `
<cdk-virtual-scroll-viewport itemSize="50" class="viewport">
<div *cdkVirtualFor="let item of items" class="item">
{{ item.name }}
</div>
</cdk-virtual-scroll-viewport>
`
})
Prefer Pure Pipes Over Methods
@Pipe ({ name : 'filterActive' , standalone : true , pure : true })
export class FilterActivePipe implements PipeTransform {
transform (items : Item []): Item [] {
return items.filter (i => i.active );
}
}
@for (item of items () | filterActive; track item.id ) { ... }
@for (item of getActiveItems (); track item.id ) { ... }
Use computed() for Derived Data
export class ProductStore {
products = signal<Product []>([]);
filter = signal ('' );
filteredProducts = computed (() => {
const f = this .filter ().toLowerCase ();
return this .products ().filter (p =>
p.name .toLowerCase ().includes (f)
);
});
}
get filteredProducts () {
return this .products .filter (p =>
p.name .toLowerCase ().includes (this .filter )
);
}
5. Server-Side Rendering (HIGH)
Configure Incremental Hydration
import {
provideClientHydration,
withIncrementalHydration,
} from "@angular/platform-browser" ;
export const appConfig : ApplicationConfig = {
providers : [
provideClientHydration (withIncrementalHydration (), withEventReplay ()),
],
};
Defer Non-Critical Content
<app-header />
<app-hero />
@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)
Use New Control Flow Syntax
@if (user()) {
<span > {{ user()!.name }}</span >
} @else {
<span > Guest</span >
} @for (item of items(); track item.id) {
<app-item [item ]="item" />
} @empty {
<p > No items</p >
}
<span *ngIf ="user; else guest" > {{ user.name }}</span >
<ng-template #guest > <span > Guest</span > </ng-template >
Avoid Complex Template Expressions
class Component {
items = signal<Item []>([]);
sortedItems = computed (() =>
[...this .items ()].sort ((a, b ) => a.name .localeCompare (b.name ))
);
}
@for (item of sortedItems (); track item.id ) { ... }
@for (item of items () | sort :'name' ; track item.id ) { ... }
7. State Management (MEDIUM)
Use Selectors to Prevent Re-renders
@Component ({
template : `<span>{{ userName() }}</span>` ,
})
class HeaderComponent {
private store = inject (Store );
userName = this .store .selectSignal (selectUserName);
}
@Component ({
template : `<span>{{ state().user.name }}</span>` ,
})
class HeaderComponent {
private store = inject (Store );
state = toSignal (this .store );
}
Colocate State with Features
@Injectable ()
export class ProductStore { ... }
@Component ({
providers : [ProductStore ],
})
export class ProductPageComponent {
store = inject (ProductStore );
}
@Injectable ({ providedIn : 'root' })
export class GlobalStore {
}
8. Memory Management (LOW-MEDIUM)
Use takeUntilDestroyed for Subscriptions import { takeUntilDestroyed } from '@angular/core/rxjs-interop' ;
@Component ({...})
export class DataComponent {
private destroyRef = inject (DestroyRef );
constructor ( ) {
this .data$ .pipe (
takeUntilDestroyed (this .destroyRef )
).subscribe (data => this .process (data));
}
}
export class DataComponent implements OnDestroy {
private subscription!: Subscription ;
ngOnInit ( ) {
this .subscription = this .data$ .subscribe (...);
}
ngOnDestroy ( ) {
this .subscription .unsubscribe ();
}
}
Prefer Signals Over Subscriptions
@Component ({
template : `<div>{{ data().name }}</div>` ,
})
export class Component {
data = toSignal (this .service .data$ , { initialValue : null });
}
@Component ({
template : `<div>{{ data?.name }}</div>` ,
})
export class Component implements OnInit , OnDestroy {
data : Data | null = null ;
private sub!: Subscription ;
ngOnInit ( ) {
this .sub = this .service .data$ .subscribe ((d ) => (this .data = d));
}
ngOnDestroy ( ) {
this .sub .unsubscribe ();
}
}
Quick Reference Checklist
New Component
Performance Review
SSR Check
Resources
When to Use This skill is applicable to execute the workflow or actions described in the overview.
Connections
Domain: [[Software Entwicklung]]
Kategorie: [[Frontend Entwicklung]]
Navigation: [[Skills Uebersicht]], [[Home]]
More from this repository
Related occupations SOC
Based on SOC occupation classification