How To Use Component Lifecycle Hooks In Angular

Component Lifecycle Hook

The number of methods called in a sequence to execute a component at specific moments is known as lifecycle hook.

COMPONENT LIFECYCLE HOOKS OVERVIEW

There are 8 different stages in the component lifecycle. Every stage is called as lifecycle hook event. So, we can use these hook events in different phases of our application to obtain control of the components.

Constructor

Since a component is a Typescript class, every component must have a constructor method. The constructor of the component class executes, first, before the execution of any other lifecycle hook events. If we need to inject any dependencies into the component, then the constructor is the best place to inject those dependencies. After executing the constructor, Angular executes its lifecycle hook methods in a specific order.
We can say that once a new component is an instantiation, Angular goes through a couple of different phases in this creation process and it will actually give us a chance to hook into these phases by implementing some methods as per our requirement.

Why we need Angular? Features & Benefits of Angular

Lifecycle Sequence

OnChange – OnInit – DoCheck – AfterContentInit – AfterContentChecked – AfterViewInit – AfterViewChecked – OnDestroy

Basically, what Angular does with a component is that it creates the component, renders the component, creates and renders the component‟s children, checks when the component’s data-bound properties change and destroys the component before removing it from the DOM. Means

Lifecycle of a component includes:

• Creating a component
• Rendering a component
• Creating and rendering its child components
• Checking data-bound properties
• Destroying and removing it from DOM

Now, try to learn all these hooks and learn how can we put our code between these phases. We need to learn only 3 steps to use lifecycle hooks, they are:
• Import Hook interfaces from „@angular/core‟ library
• Declare that component/directive implements lifecycle hook interface
• Create the hook method and define the functionality of that method.

How to Make Reusable Components in Angular | Reusable Components

ngOnChange:

It is always called whenever one of our bound input changes; i.e., changes occur on those properties which are decorated with @Input() method.
Actually whenever we communicate between parent and child component, then the passing property from parent component is always received by child component with @Input decorator.
When the parent changes the Input properties, then this hook is invoked in the child component and we can easily find out the details about which input properties have changed and how they have changed.
ngOnChanges()
• Used in pretty much any component that has an input.
• Called whenever an input value changes
• Is called the first time before ngOnInit

ngOnInit():

ngOnInit() methods can be executed once component has been initialized, i.e. whenever component is created it triggers it. This hook is fired after ngOnChanges() and before any of the child directive properties are initialized. There is a place where we will put logic related to initialization of properties.
ngOnInit()
• Used to initialize data in a component.
• Called after input values are set when a component is initialized.
• Added to every component by default by the Angular CLI.
• Called only once

ngDoCheck():

Whenever something changes on the template of a component or inside the component then ngDoCheck() executes. We can also say that it is called during every change detection run. This hook is called after ngOnInit().
Actually, this is very similar to ngOnChanges() hook, the major difference is that ngOnChanges() does not detect all the changes made to the input properties. It detects changes for those properties which are passed by value. However, ngDoCheck() detects changes for those properties also which are passed by reference such as arrays.
ngDoCheck()
• Called during all change detection runs
• A run through the view by Angular to update/detect changes

ngAfterContentInit():

This is called whenever the content which is projected through ng-content has been initialized. Here, content projected means a way to import HTML content from outside the component and insert that content into the content‟s template in a designated spot and this spot is identified by Angular with the help of , i.e. it can put the content‟s template where is present.

ngAfterContentInit()

• Called only once after first ngDoCheck()

• Called after the first run through of initializing content

ngAfterContentChecked():

It is executed whenever the change detection occurs i.e. content will be projecting into our component. It is called immediately after the ngAfterContentInit and after every subsequent ngDoCheck().
ngAfterContentChecked()
• Called after every ngDoCheck()
• Waits till after ngAfterContentInit() on first run through

ngAfterViewInit():

Angular ngAfterViewInit() is the method of AfterViewInit interface.
ngAfterViewInit() is a lifecycle hook that is called after Angular has fully initialized a component’s views. ngAfterViewInit() is used to handle any additional initialization tasks.
It is called after the component’s view (and child view) has been initialized. It is very similar to ngAfterContentInit, but it works on view that is whenever view is initialize it fires.
ngAfterViewInit()

  1. Called after Angular initializes component and child component content.
  2. Called only once after view is initialized
    ngAfterViewInit() is used to access properties annotated with @ViewChild() and @ViewChildren()
    decorators.

ngAfterViewChecked():

It fires after ngAfterViewInit() and every time the view (and child view) have been checked. This hook is fired after the ngAfterViewInit and after that for every subsequent ngAfterContentChecked hook. As per the name it both will run with View i.e. whenever view (template) is initialized and if some changes
occur.
ngAfterViewChecked()
• Called after all the content is initialized and checked. (Component and child components).
• First call is after ngAfterViewInit()
• Called after every ngAfterContentChecked() call is completed

ngOnDestroy():

This hook is called once the component or directive is about to destroy. Generally, we put logic related to clean up here. This is the right place where we would like to Unsubscribe Observable and detach event handlers to avoid memory leaks.
ngOnDestroy()
Used to clean up any necessary code when a component is removed from the DOM. Fairly often used to unsubscribe from things like services.
Called only once just before component is removed from the DOM.

Leave a Reply

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