Coding exercise: debug unnecessary component rendering in Angular.

Angular practical coding · Experienced

Model answer

First measure. Angular DevTools has a Profiler that shows which components ran change detection and how long it took. Then fix the cause.

The usual fixes: use ChangeDetectionStrategy.OnPush so a component is checked only when its inputs change, an event fires inside it, or a signal it reads changes; do not call functions or build new arrays in the template (they run on every check); use track in @for so rows are reused; and move heavy work into computed signals.

// Before: the method runs on every change detection, and the list is rebuilt each time
// <li *ngFor="let u of getActive()">{{ u.name }}</li>
class Before { getActive() { return this.users.filter((u) => u.active); } }

// After: OnPush, a computed signal and a track expression
@Component({
  selector: 'app-users',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<ul>@for (u of active(); track u.id) { <li>{{ u.name }}</li> }</ul>`,
})
export class Users {
  users = input.required<{ id: number; name: string; active: boolean }[]>();
  active = computed(() => this.users().filter((u) => u.active));
}

With OnPush, change objects instead of mutating them, or the view will not update. Zoneless change detection (provideZonelessChangeDetection) goes further by running checks only when signals or events say so; check the Angular documentation for its status in your version.

Tips

Practise it yourself in the React and Angular code playground.

Learn this topic

Angular Tutorial: Beginner to Advanced .

Sign in to add your own answer.

More questions