Following best practices and optimizing your Angular applications improves performance, maintainability, and scalability. These practices cover coding standards, change detection, lazy loading, and efficient module design.
? Goal: Fast, scalable, maintainable Angular apps
OnPush where possible to reduce unnecessary checks.trackBy in *ngFor: Optimize DOM rendering for large or frequently changing lists.async Pipe: Use async pipe to manage subscriptions automatically.By default, Angular runs change detection for many events (like clicks, HTTP responses, timers, etc.). With ChangeDetectionStrategy.OnPush, Angular only checks a component when:
@Input() reference changes.async pipe emits a new value.ChangeDetectorRef).Lazy loading lets you split your app into smaller bundles and load feature modules only when the user navigates to them. This improves the first load time and overall performance, especially in large applications.
trackByWhen rendering lists with *ngFor, Angular re-renders items when the array changes. Using trackBy helps Angular reuse DOM elements based on a unique identifier (like id), which significantly improves performance for large lists.
// Child component using OnPush change detection
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>{{ data }}</p>',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
@Input() data!: string;
}
ChangeDetectionStrategy.OnPush tells Angular to run change detection only when input references change.ChildComponent will not be re-checked on every global event, improving performance.
// App routing module with a lazy loaded Admin feature module
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.module').then(m => m.AdminModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
AdminModule is only downloaded when the user navigates to /admin.async pipe over manual subscribe() to avoid memory leaks.ReportsModule) and implement lazy loading with routing.ChangeDetectionStrategy.OnPush and the async pipe for observable data.trackBy in a list component to optimize DOM rendering for large datasets, using a unique id for each item.