Lifecycle Hooks in Angular
VCIDevTeam
Posted on March 28, 2023
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:
- Constructor
- OnChanges
- OnInit
- DoCheck
- OnDestroy And these are the hooks for the component's children:
- AfterContentInit
- AfterContentChecked
- AfterViewInit
- AfterViewChecked
So now, we will create a simple example with an input and a button.
Firstly, create an HTML interface in the app.component!
And similarly the OnSubmit handler function in app.component.ts
Then we instantiate a demo component, this is where we will demo the main lifecycle hooks.
The html file in the demo component.
The .ts file with the import of the lifecycle hooks we will be using.
Call it in the HTML file of the app.component like this.
And we have a simple interface.
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.
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.
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.
ngOnInit
Let's return to the.ts file and proceed using ngOnInit in that sequence!
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.
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.
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.
ngAfterContentInit
Once the component's content DOM initializes, ngAfterContentInit triggers (first load).
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.
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.
Additionally, ngafterContentChecked is called when a component is first started. It occurs immediately following ngafterContentInit. Via change detection, ngafterContentChecked can be re-enabled.
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.
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.
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.
The manner ngAfterViewChecked will be executed again varies with each cycle.
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
app.component.ts file
And finally demo.component.ts file
We will have an interface like this
We could see that OnDestroy hasn't been called yet but after clicking the Destroy button.
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
Posted on March 28, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.