In Angular, lifecycle hooks are special methods that allow you to tap into key moments of a component or directive’s life — from creation to destruction. These hooks let you execute custom logic at specific points in the component’s life cycle. Angular provides several built-in hooks. Here’s a structured breakdown:
1. ngOnChanges
- Called: Whenever Angular sets or resets input properties (
@Input
). - Purpose: Respond to changes in input properties.
- Signature:
ngOnChanges(changes: SimpleChanges) { // code to respond to input changes }
2. ngOnInit
- Called: Once after the first ngOnChanges.
- Purpose: Initialize the component after Angular first displays the data-bound properties.
- Example:
ngOnInit() { console.log('Component initialized'); }
3. ngDoCheck
- Called: During every change detection run, after
ngOnChanges
andngOnInit
. - Purpose: Detect and act on changes that Angular cannot or does not detect automatically.
- Example:
ngDoCheck() { console.log('Change detection run'); }
4. ngAfterContentInit
- Called: Once after content projection (ng-content) is initialized.
- Purpose: Initialize logic dependent on projected content.
- Example:
ngAfterContentInit() { console.log('Projected content initialized'); }
5. ngAfterContentChecked
- Called: After every check of projected content.
- Purpose: Respond to changes in projected content.
- Example:
ngAfterContentChecked() { console.log('Projected content checked'); }
6. ngAfterViewInit
- Called: Once after the component’s view and child views are initialized.
- Purpose: Initialize logic dependent on the component’s view (like querying
@ViewChild
). - Example:
@ViewChild('myDiv') myDiv: ElementRef; ngAfterViewInit() { console.log(this.myDiv.nativeElement.innerText); }
7. ngAfterViewChecked
- Called: After every check of the component’s view and child views.
- Purpose: Respond to changes in the view.
- Example:
ngAfterViewChecked() { console.log('View checked'); }
8. ngOnDestroy
- Called: Just before Angular destroys the component.
- Purpose: Cleanup (unsubscribe from observables, detach event handlers, etc.).
- Example:
ngOnDestroy() { console.log('Component destroyed'); }
Lifecycle Flow Summary
For a component with inputs:
ngOnChanges → ngOnInit → ngDoCheck → ngAfterContentInit →
ngAfterContentChecked → ngAfterViewInit → ngAfterViewChecked → ... → ngOnDestroy