count displayed in the template. What does Angular do during change detection?import { Component } from '@angular/core'; @Component({ selector: 'app-counter', template: `<p>Count: {{ count }}</p>` }) export class CounterComponent { count = 0; }
Angular's change detection compares the current and previous values of properties used in the template. If a value changed, Angular updates the DOM to show the new value. This keeps the UI and data in sync efficiently.
increment() once?import { Component } from '@angular/core'; @Component({ selector: 'app-clicker', template: `<button (click)="increment()">Click me</button><p>Clicks: {{ clicks }}</p>` }) export class ClickerComponent { clicks = 0; increment() { this.clicks++; } }
When increment() runs, it adds 1 to clicks. Angular detects this change and updates the displayed text to show the new value.
import { Component } from '@angular/core'; @Component({ selector: 'app-async', template: `<p>Message: {{ message }}</p>` }) export class AsyncComponent { message = 'Waiting...'; ngOnInit() { setTimeout(() => { this.message = 'Done!'; // What else is needed here? }, 1000); } }
setTimeout and runs change detection after it.Angular patches browser APIs like setTimeout to run change detection automatically after the callback. So no manual trigger is needed here.
user.name?import { Component } from '@angular/core'; @Component({ selector: 'app-user', template: `<p>Name: {{ user.name }}</p><button (click)="changeName()">Change Name</button>` }) export class UserComponent { user = { name: 'Alice' }; changeName() { this.user.name = 'Bob'; } }
Angular's default change detection checks object references, not deep property changes. Changing a nested property without changing the object reference may not trigger view update.
ChangeDetectionStrategy.OnPush in Angular components?OnPush tells Angular to skip checking the component unless its input properties change by reference or an event inside it happens. This reduces unnecessary checks and boosts performance.