Sub topic 2
How Change Detection Drives Angular Lifecycle Hooks
Prerequisites: basic TypeScript, Angular components and templates, property binding, and RxJS subscriptions.
How Change Detection Drives the Hooks
Angular uses change detection to check whether a component's data requires an updated view. During a check, Angular walks the component tree and runs lifecycle hooks at specific points. A hook is a method that Angular calls automatically.
For a component's first check, the important order is:
ngOnChanges, when an input has a value.ngOnInit.ngDoCheck.ngAfterContentInit.ngAfterContentChecked.ngAfterViewInit.ngAfterViewChecked.
Later checks usually run ngOnChanges only when an input changes, followed by ngDoCheck, ngAfterContentChecked, and ngAfterViewChecked.
Custom Change Checks with ngDoCheck
ngDoCheck runs during every change-detection check. Use it only when Angular's normal input comparison does not detect the change you need, such as a mutation inside an object or array.
Keep this method very cheap. Do not perform network requests or repeated expensive calculations there.
export class FilterComponent implements DoCheck {
private previousLength = 0;
items: string[] = [];
ngDoCheck(): void {
if (this.items.length !== this.previousLength) {
this.previousLength = this.items.length;
console.log('Item count changed');
}
}
}Projected Content: AfterContent Hooks
Projected content is content supplied through <ng-content>. Use ngAfterContentInit once to access projected content after Angular creates it. Use ngAfterContentChecked for later checks, but avoid changing bound values there.
The Component's Own View: AfterView Hooks
The component view is its own template and its child views. ngAfterViewInit runs once after the view exists, so view queries such as @ViewChild are safe there. ngAfterViewChecked runs repeatedly and should remain lightweight.
Cleaning Up with ngOnDestroy
ngOnDestroy runs once before Angular removes the component. Unsubscribe from manual subscriptions and clear timers or event listeners there. Automatic cleanup with DestroyRef is often simpler for modern Angular code.
Exercise
Which hook should contain cleanup for a timer created by a component?
Show answer
Put the cleanup in ngOnDestroy, or tie the timer to DestroyRef with takeUntilDestroyed.