Lifecylce Hooks in Angular

Lifecylce Hooks in Angular

In this tutorial, we will learn about life cycle hooks in Angular 12+

What is Lifecycle?

Angular components enter its lifecycle from the time it is created to the time it is destroyed.

Angular hooks provide ways to tap into these phases and trigger changes at specific phases in a lifecycle.

Constructor:

1.NgOnChanges

This method is called whenever one or more input properties of the component changes.

The hook receives a SimpleChanges object containing the previous and current values of the property.

This is the Only Lifecycle hooks that work with arguments

2.NgOnInit

This hook gets called once, after the ngOnChanges hook.

It initializes the component and sets the input properties of the component.

3.NgDOChek

 It gets called after ngOnChanges and ngOnInit and is used to detect and act on changes that cannot be detected by Angular.

Ngdocheck calls on any change made on component like, button click, input change.

We can implement our change detection algorithm in this hook.

4.NgAfterContentInit()

 It gets called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component.

5. NgAfterContentChecked

It gets called after ngAfterContentInit and it responds whenever our content changes means value of ng-content gets changed.

6.NgAfterViewInit

It responds after a component’s view, or a child component’s view is initialized.

7.NgAftetrViewChecked

It gets called after ngAfterViewInit, and it responds after the component’s view, or the child component’s view is checked.

8.NgOnDestroy

 It gets called just before Angular destroys the component. This hook can be used to clean up the code and detach event handlers.

For Example, if you have started set interval on one component then move to another component then you must have to stop when component destroy else it will continue execution

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment