Introduction
Change detection helps Angular know when to update what you see on the screen. It keeps your app fresh and in sync with your data.
Change detection helps Angular know when to update what you see on the screen. It keeps your app fresh and in sync with your data.
Angular automatically runs change detection to update the view when data changes.
count and updates the number shown.@Component({
selector: 'app-counter',
template: `
<button (click)="count = count + 1">Add</button>
<p>Count: {{ count }}</p>
`
})
export class CounterComponent {
count = 0;
}updateMessage() changes message, and Angular updates the displayed text automatically.@Component({
selector: 'app-message',
template: `
<p>{{ message }}</p>
`
})
export class MessageComponent {
message = 'Hello!';
updateMessage() {
this.message = 'Hi there!';
}
}This component shows a button and a count. Each time you click, Angular detects the change in clicks and updates the number shown.
import { Component } from '@angular/core'; @Component({ selector: 'app-click-counter', template: ` <button (click)="increment()">Click me</button> <p>You clicked {{ clicks }} times.</p> ` }) export class ClickCounterComponent { clicks = 0; increment() { this.clicks++; } }
Change detection runs after events like clicks, HTTP responses, or timers.
You can optimize performance by controlling when Angular checks for changes.
Change detection keeps your app's screen updated with the latest data.
Angular does this automatically after user actions or data updates.
Understanding it helps you build smooth and responsive apps.
export function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return `Count: ${count}`;
}increment() is called but Angular's change detection does not run?import { ChangeDetectorRef } from '@angular/core';
@Component({ selector: 'app-test', template: `{{value}}
` })
export class TestComponent {
value = 0;
constructor(private cdr: ChangeDetectorRef) {}
update() {
this.value = 1;
// Missing change detection trigger here
}
}value not update after calling update()?Pass the test and this pattern moves unknown