Change Detection is the mechanism Angular uses to detect changes in a component's data and update the view accordingly.
typescript
import { ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
// Default Change Detection (checks all the time)
@Component({
selector: 'app-default',
template: `<p>{{ data }}</p>`
})
export class DefaultComponent {
data = 'Hello';
}
// OnPush Change Detection (checks only when @Input changes)
@Component({
selector: 'app-optimized',
template: `<p>{{ data }}</p>`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizedComponent {
@Input() data: any;
constructor(private cdr: ChangeDetectorRef) {}
// Manually trigger change detection if needed
updateData() {
this.data = 'New value';
this.cdr.markForCheck(); // Tell Angular to check
}
}You should see
(Using the OnPush strategy improves performance by cutting down unnecessary checks)