Lifecycle hooks in Angular

How and where to use lifecycle is our Angular application?

Every component has his own lifecycle. To handle data in different stages of component Angular providing us life cycle hooks. With this hooks we can do multiple things according to our application needs. Check console for lifecycle hooks effect.

# Hook method Last
1 ngOnChanges() Respond when Angular sets or resets data-bound input properties. The method receives a SimpleChanges object of current and previous property values. if your component has no inputs or you use it without providing any inputs, the framework will not call ngOnChanges().
2 ngOnInit() Initialize the directive or component after Angular first displays the data-bound properties and sets the directive or component’s input properties.
3 ngDoCheck() Detect and act upon changes that Angular can’t or won’t detect on its own.
4 ngAfterContentInit() Called once after the first ngDoCheck(
5 ngAfterContentChecked() Respond after Angular checks the content projected into the directive or component.
6 ngAfterViewInit() Respond after Angular initializes the component’s views and child views, or the view that contains the directive.
7 ngAfterViewChecked() Respond after Angular checks the component’s views and child views, or the view that contains the directive.
8 ngOnDestroy() Cleanup just before Angular destroys the directive or component. Unsubscribe Observables and detach event handlers to avoid memory leaks.

Demo Githhub Stackblitz

Leave a Reply

Your email address will not be published. Required fields are marked *