DEV Community

VCIDevTeam
VCIDevTeam

Posted on

Lifecycle Hooks in Angular

Continuing the series of Angular in web application development, in this part 3 we will dive into another special feature in Angular: lifecycle hooks.

What are Lifecycle Hooks?

Lifecycle hooks allow us to connect and run code at a specific lifecycle event of a component or directive.

Angular is in charge of all the components of directives that it creates, updates, or deletes for us. So with the use of the lifecycle hooks, we can gain better control of our application.

For that, we use some "hooks" methods with a prefixed of ng to our component or directive. And these "hooks" are split into two different kinds: hooks for components or directives and hooks for child components.

The lifecycle

The following are the hooks for components or directives in the usual order:

  1. Constructor
  2. OnChanges
  3. OnInit
  4. DoCheck
  5. OnDestroy And these are the hooks for the component's children:
  6. AfterContentInit
  7. AfterContentChecked
  8. AfterViewInit
  9. AfterViewChecked

Image description

So now, we will create a simple example with an input and a button.

Firstly, create an HTML interface in the app.component!

Image description
And similarly the OnSubmit handler function in app.component.ts
Image description
Then we instantiate a demo component, this is where we will demo the main lifecycle hooks.
The html file in the demo component.
Image description
The .ts file with the import of the lifecycle hooks we will be using.
Image description
Call it in the HTML file of the app.component like this.
Image description
And we have a simple interface.
Image description
We can see in the console log that the Constructor has been called so we will start with what is the Constructor.

Constructor

Constructor is the class's default method when it is first created. Instead of using it to handle the logic in this function, it should be used to define Dependency Injection.

NgOnchange

Next, we'll edit demo.compont.ts using Onchange.
Image description
After changing @Input bound class components, ngOnChanges is called. The @Input() decorator binds data from an external source. The @Input property is passed once more when the external source modifies the data in a recognizable way.
Image description
The moment we alter the input, ngOnChanges will launch. It also happens when the input data is initialized. SimpleChanges is the sort of optional argument that the hook accepts. Information regarding the modified input limit properties is contained in this value.
Image description

ngOnInit

Let's return to the.ts file and proceed using ngOnInit in that sequence!
Image description
Initializing the component's input bound property (@Input) causes ngOnInit to trigger once. In this illustration, when the demo receives input, the hook does not activate. It activates instead as soon as the data renders the application.
Image description
As we can see, when we initialize in the constructor for the demo, the value has the value "demo," but when we update OnInIt, the value has changed to " " in the app.component.
The hook ngOnInit is one-and-done. Its primary concern is initialization.

ngDoCheck

Every change detection cycle causes ngDoCheck to trigger. Recognize regular changes. Every time change detection is run, do any action; it will catch DOM events (click, hover), setTimeout, setInterval, or XHR requests. Every time Angular detects a change, ngDoCheck is called, so we must use it carefully because, if implemented improperly, it can lead to performance issues.
Image description
Every additional change loop that ngDoCheck executes after Angular has finished running and before we change the data is equivalent.

Next are the hooks for the child components

We will add an h1 tag with the inputText data binding.
Image description

ngAfterContentInit

Once the component's content DOM initializes, ngAfterContentInit triggers (first load).
Image description
Begin using AppComponent. DemoComponent must be rendered for AppComponent to be finished. The ng-content>/ng-content> element of DemoComponent projects the content contained within its element. The rendered content completes rendering, and ngAfterContentInit fires. Subsequently, DemoComponent completes rendering, followed by AppComponent, and ngAfterContentInit does not fire once more.
Image description

ngAfterContentChecked

DOM targeting change detection cycles are followed by the ngAfterContentChecked event. Developers may now simplify the way the DOM reacts to change detection. Performance problems might result from ngafterContentChecked firing repeatedly.
Image description
Additionally, ngafterContentChecked is called when a component is first started. It occurs immediately following ngafterContentInit. Via change detection, ngafterContentChecked can be re-enabled.
Image description

ngAfterViewInit

Once the DOM view has finished initializing, ngAfterViewInit begins. View begins to load immediately after content. ngAfterViewInit is frequently used to run a view query with a reference to viewChild or viewChilden.
Image description
Render in the aforementioned example begins with AppComponent. The DemoComponent must be rendered for the AppComponent to be finished. The ng-content>/ng-content> element of DemoComponent projects the material contained within its element. When the rendered content and DemoComponent have completed rendering, ngAfterViewInit fires, and after AppComponent has finished rendering, ngAfterViewInit will not fire once again.
Image description

ngAfterViewChecked

During each change detection cycle to the component's View, ngAfterViewChecked is triggered. Developers may participate in the process of helping to identify changes impacting the DOM view by using the ngAfterViewChecked function.
Image description
The manner ngAfterViewChecked will be executed again varies with each cycle.
Image description

ngOnDestroy

ngOnDestroy terminates the lifecycle hooks. But first, we must use a button in the html to add the Destroy function to the app.compont. Because only when a component or directive is destroyed will OnDestroy be invoked.
app.component.html file
Image description
app.component.ts file
Image description
And finally demo.component.ts file
Image description
We will have an interface like this
Image description
We could see that OnDestroy hasn't been called yet but after clicking the Destroy button.
Image description
DemoComponent passes false. The evaluation of the *ngIf structural directive is false. ngOnDestroy executes, and ngIf deletes its p> and /p>. Any number of button clicks will cause destruction to be set to false in this process.

Order of execution of lifecycle hooks when components are nested

When components are related to one another as parents and children, each component runs its own lifecycle hooks. Whichever is called first, related lifecycle hooks in that component are executed first. Nevertheless, there is a preset executor for each hook, such as:

  • The parent component starts running before the child component when using ngOnit and ngDoCheck.

  • When using ngDestroy, the son runs first and then the parent component destroys all of the child components.

  • The child components run first and then the parent component when using ngAfterViewInit and ngAfterViewChecked

The intriguing series' third and final installment on lifespan hooks is now complete. We appreciate your time and will see you in the next section.

By,
VNPT Cyber Immunity - VCI

Top comments (0)