The Lifecycle Hooks makes every complex state management easier and simpler, so let's explore the Lifecycle Hooks of Angular to fine-tune the behavior of our components.
5. ngOnChanges
● Purpose:
○ Respond when Angular (re)sets data-bound input properties.
○ Tracks current and Previous values.
○ Only tracks @Input property values.
● Timing:
○ Called before ngOnInit() and everytime the input changes!
● Limitations:
○ Fails to detect changes user Object types.
5
7. ngOnInit
● Purpose:
○ Respond when Angular first displays the data-bound properties.
○ To Perform initialization shortly after constructor.
○ To set up the component after Angular sets the input properties.
○ One-and-Done Hook!
● Timing:
○ Called only once after the first ngOnChanges().
● Limitations:
○ A directive’s input properties are not set until constructor().
7
9. ngDoCheck
● Purpose:
○ Detect when Angular doesn’t detect on its own.
○ Compares current state against previous values.
● Timing:
○ Called during every change detection run.
○ Called immediately after ngOnChanges() and ngOnInit()..
● Limitations:
○ Called with an enormous frequency.
○ Dependency must be very less or the user experience suffers.
9
11. ngAfterContentInit
● Purpose:
○ Respond when Angular projects external content into the
component’s view.
○ To Perform additional initialization tasks shortly after content
projection.
● Timing:
○ Called only once after Angular fully initialized all the contents.
11
13. ngAfterContentChecked
● Purpose:
○ Respond when change detector completes the content checking.
○ To Perform tasks after every content checking.
● Timing:
○ Called after every content check in the directive.
● Limitations:
○ Instantiated before the changes in child component.
AfterContent => @ContentChild decorator
13
15. ngAfterViewInit
● Purpose:
○ Respond when Angular fully initialized a component’s view.
○ To Perform tasks after all set in the view.
● Timing:
○ Called immediately after view initialization.
● Limitations:
○ Invoked only once after the view is initialized.
15
17. ngAfterViewChecked
● Purpose:
○ Respond when change detector completes the component’s view
checking.
○ To Perform tasks after every content checking.
● Limitations:
○ Called even when there is no changes so performance issues.
AfteView => @ViewChild decorator
17
19. ngOnDestroy
● Purpose:
○ Cleanup just before Angular destroys the component.
○ Time to notify the other components.
○ Unsubscribe observables, detach DOM events, stop Interval
Timers, free up the memory leaks and resources.
○ Vital Hooks.
● Timing:
○ Called just before Angular destroys the component.
19
20. Post-Requisites
1. What are the advantages of using
Lifecycle hooks?
2. And What are the limitations?
Note
● Should Always remember the purpose and
timing of every Hooks!
20