Lifecycle Hooks in Angular
Tags: angular, beginners, codenewbie
Published: 2023-03-28 03:02:13

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:
1. AfterContentInit
2. AfterContentChecked
3. AfterViewInit
4. AfterViewChecked

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1oghey2gfhgusn1bhig.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o4etlq47jvwbsqetws5y.png)
And similarly the OnSubmit handler function in app.component.ts
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/01c8gxd7tekusxjdii7r.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpfeh191s3alq3n9pbt4.png)
The .ts file with the import of the lifecycle hooks we will be using.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/urtt1fjpm5mvg9rl4ix6.png)
Call it in the HTML file of the app.component like this.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6z9mib2ibpbnf9syz3s.png)
And we have a simple interface.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7aqob5om5e3kg2iinf7y.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9616n83fcep8yihh5ffq.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mr35ogguq02hji6tw5vk.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nx3ljxif9vjl8z0pprrr.png)
### ngOnInit
Let's return to the.ts file and proceed using ngOnInit in that sequence!
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qh3t5murofkhi3hemsov.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cy3rv4e7wd25qmnyy6f7.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u614xozclsxbvg16a39c.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tfhuh5yk5thqmnaz7812.png)
### ngAfterContentInit
Once the component's content DOM initializes, ngAfterContentInit triggers (first load).
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dp6wne01xxgaqjzil7kw.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tup2rq7wdj1mnz2yl86n.png)
### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fjrxo8l9nkr4wycj8q1l.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uosjukjthavew1irex46.png)
### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txvhlw2rr3qd9r2gy53n.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/12p2z1namdnzpu5i4p8i.png)
### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/te9eyxfuwhzk4to4b8io.png)
The manner ngAfterViewChecked will be executed again varies with each cycle.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0q5qgd3i80nhx179i5uh.png)
### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gv5hporsdaxwjad45cyf.png)
app.component.ts file
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ohk0cuj8vyosik1aqf6.png)
And finally demo.component.ts file
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v05nmxfxhl2m72xiy2ja.png)
We will have an interface like this
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9iaza6ofsvozna4xeq7c.png)
We could see that OnDestroy hasn't been called yet but after clicking the Destroy button.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbl86784z43z3ys4ts6j.png)
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