Component Lifecycle Hooks

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Angular lifecycle hooks

explained
March 26, 2021 11 min read

See how LogRocket's AI-powered error tracking works


no signup required
Check it out

Lifecycle hooks are a special functionality in Angular that allow us to “hook into” and run
code at a specific lifecycle event of a component or directive.

Angular manages components and directives for us when it creates them, updates them, or
destroys them. With lifecycle hooks, we can gain better control of our application.

To do this, we add some specific hook methods prefixed with ng to our component or
directive. These hooks are split into two types: hooks for components or directives and hooks
for child components.
What we will learn
This article will cover the following:

 The different lifecycle hooks for Angular components and directives


 How to hook into component lifecycles to run our code
 What triggers lifecycle hooks and the order in which they are called

These are the hooks for components or directives, in call order:

1. constructor()
2. OnChanges
3. OnInit
4. DoCheck
5. OnDestroy

And these are the hooks for a component’s children components:

1. AfterContentInit
2. AfterContentChecked
3. AfterViewInit
4. AfterViewChecked

Below is a summary of the Angular lifecycle hooks in a table:

OnChanges Called when the input properties have changed

OnInit Called on initialization

DoCheck Developer’s custom change detection

OnDestroy Called before the component is destroyed

AfterContentInit Called when the component’s content ngContent is initialized

AfterContentChecked Called when the component’s content is updated or checked for updates

AfterViewInit Called when the component’s projected view has been initialized

AfterViewChecked Called after the projected view has been checked

Hooks for components or directives


In Angular, components are the smallest units of building blocks for a component tree. This
enables us to develop and maintain our codebase very easily. Components are classes with
the @Component() decorator on the them, like so:

@Component({
selector: "app-comp",
template: `<div>AppComponent</div>`,
styles: ``
})
class AppComponent implements OnInit {
//...
}
Directives are technically components, but they operate on the non-UI part of the DOM.
Their work is to add extra functionality to the DOM. Directives are also classes, but
decorated with the @Directive() class decorator.

Examples of in-built directives are *ngFor , *ngIf, etc. We can create our own directive by
doing this:

@Directive({
selector: '[highlight-text]'
})
export class HighlightDirective {
//...
}
The following are lifecycle hooks for components or directives, with explanations of how
they work and how to use them.

Constructor()
This is the constructor we are familiar with in JS classes. It is included because our
components/directives are JavaScript classes with either
an @Component or @Directive decorator. So this constructor is called when our
component/directive instance is created by Angular using the new keyword.

OnChanges
OnChanges is a lifecycle hook that is called when any data-bound property of a directive
changes. An ngOnChanges() method must be defined to handle the changes.

Let’s say our BComponent has the input property books:

@Component({
selector: 'bcomp',
template: `
<div *ngFor="let book of books">
{{book}}
</div>
`
})
export class BComponent implements OnChanges {
@Input() book
ngOnChanges() {
console.log("The book property changed")
}
}
@Component({
// ...
template: `
<bcomp [books]="books"></bcomp>
`
})
export class App {
books = ["Michael Crichton: Prey"]
}
App bound its books property to BComponent’s books. Note how we implemented
the OnChanges interface and added the ngOnChanges method. ngOnChanges will be
called by Angular when the books property it receives from the App component has
changed.

If we mutate the books property in the App component, Angular will not pick it up, and
the ngOnChanges in the BComponent will not be run:

@Component({
// ...
template: `
<bcomp [books]="books"></bcomp>
`
})
export class App {
books = ["Michael Crichton: Prey"]
constructor() {
setInterval(()=> {
this.books.push("New Book: " + Date.now())
}, 1000)
}
}
The push method is a mutating method, and with the above code, BComponent will not pick
up any changes and ngOnChanges will not be run.

As the BComponent is not an OnPush CD strategy, its view will be updated but the new
book added to books will not be displayed, because Angular updates a component/directive
input bindings before the updating it DOM.

We should be aware of immutability and always try to return a new state/reference. We will
use a non-mutating method called Array#concat:
@Component({
// ...
template: `
<bcomp [books]="books"></bcomp>
`
})
export class App {
books = ["Michael Crichton: Prey"]
constructor() {
setInterval(()=> {
this.books = this.books.concat(["New Book: " + Date.now()])
}, 1000)
}
}
Now, the ngOnChanges on BComponent will be run.

Over 200k developers use LogRocket to create better digital experiences

Learn more →

Very simply, ngOnChanges is run when the component/directive’s input bindings have
changed.

OnInit
OnInit is a lifecycle hook that is called after Angular has initialized all data-bound
properties of a directive. Define an ngOnInit() method to handle any additional
initialization tasks.

This hook is called when the first change detection is run on the component. After the first
run it is switched off never to be run again. It is a best practice to add our initialization logic
here.

To hook into this, we will implement the OnInit interface and add ngOnInit method in our
component/directive:

@Component({
//...
})
export class BComponent implements OnInit {
ngOnInit() {
console.log("ngOnInit called")
}
}
What’s the difference between constructor and OnInit?
Constructor and OnInit seem the same, but they are called at different phases. Angular
has two phases: the bootstrapping phase and the change detection phase.

The constructor is called at the bootstrapping phase. This phase is when Angular creates the
instances of services, pipes, components, and directives in our module. Angular initializes the
component and resolves its dependencies and passes it to the constructor.

The change detection phase happens after the bootstrapping phase when Angular finally calls
the tick method ApplicationRef#tick.

What is change detection? This is a mechanism whereby Angular detects a change in the state
of a component/directive and updates the DOM to reflect as such. Angular detects this
using Zone.js, a library that monkey-patches the following asynchronous APIs in the
browser:

 setTimeout, clearTimeout, setInterval, etc.


 The AJAX XMLHttpRequest object

At the change detection phase, these hooks are called in sequence:

 OnInit
 DoCheck
 OnChanges

Proof:

// https://github.com/angular/packages/core/src/view/provider.ts
export function checkAndUpdateDirectiveDynamic(
view: ViewData, def: NodeDef, values: any[]): boolean {
const providerData = asProviderData(view, def.nodeIndex);
const directive = providerData.instance;
let changed = false;
let changes: SimpleChanges = undefined !;
for (let i = 0; i < values.length; i++) {
if (checkBinding(view, def, i, values[i])) {
changed = true;
changes = updateProp(view, providerData, def, i, values[i],
changes);
}
}
if (changes) {
directive.ngOnChanges(changes);
}
if ((def.flags & NodeFlags.OnInit) &&
shouldCallLifecycleInitHook(view,
ViewState.InitState_CallingOnInit, def.nodeIndex)) {
directive.ngOnInit();
}
if (def.flags & NodeFlags.DoCheck) {
directive.ngDoCheck();
}
return changed;
}
So, the OnInit is called after the component tree has been constructed, and the dependencies
are resolved and passed to the component/directive’s instances. After being called, it is
switched off.

What do we mean by being switched off? Each component/directive in Angular has view
states:

export const enum NodeFlags {


OnInit = 1 << 16,
OnDestroy = 1 << 17,
DoCheck = 1 << 18,
OnChanges = 1 << 19,
AfterContentInit = 1 << 20,
AfterContentChecked = 1 << 21,
AfterViewInit = 1 << 22,
AfterViewChecked = 1 << 23,
// ...
}
The above is a bitmask of a view state. Internally, components/directives are referred to as a
view. Each components’ view is created with view states depending on the lifecycle hook it
implemented. A view state can be the combination of any of the above bitmasks. Note that
each hook has a bitmask.
Lifecycle Hooks in Angular- A
Complete Guide
Blog Author
Bala Krishna Ragala
Published
05th Sep, 2023
Views
9,473
Read Time
10 Mins
In this article

1. What are Angular Component Lifecycle Hooks?


2. The Different Lifecycle Hooks For Angular Components And
Directives
3. How to Use Lifecycle Hooks
4. The Order of Execution of Life Cycle Hooks
5. Angular Lifecycle Hook Example
6. Conclusion
7. Frequently Asked Questions (FAQs)

View All
Angular lifecycle hooks begin with the instantiation of the component class by Angular.
The component view and its children are then rendered. When Angular detects a change in
data-bound attributes, it changes the display and the component instance, completing the
life cycle. Once the component instance is destroyed, and its displayed template is
removed from the DOM, the lifespan terminates.

In the same way that Angular builds, modifies and destroys objects during execution,
directives have a similar lifetime. For better understanding you may check out an angular
training course.

Angular applications can utilize lifecycle hook functions to access and react to critical
events in the lifetime of an element or directive. These events include initialization,
detection of changes, and clean up before deletion. To know more about angular lifecycle
hooks, keep reading.

What are Angular Component Lifecycle Hooks?


The root component of lifecycle hooks in angular is created and rendered when the angular
application starts. Then it generates and renders its offspring and the offspring of its
offspring. Components are organized into a tree.

Once the components are loaded, Angular begins producing the view. The input attributes
must be verified, data bindings and expressions evaluated, and projected content rendered,
among other things. Angular removes the component from the document object model
(DOM) as soon as the component is no longer required; Angular removes it from the
document object model (DOM).

Angular provides us with lifecycle hooks that notify us when certain events occur.

In the Angular component life cycle, angular lifecycle hooks are nothing more than
callback functions that Angular calls when a particular event happens.

As an example,

 When Angular initially initializes a component, it calls ngOnInit.


 Angular calls nonchanges whenever an input property of a component changes.
 On component destruction, ngOnDestroy is called.
Below mentioned are the angular lifecycle hooks.

 ngOnChanges
 ngOnInit
 ngDoCheck
 ngAfterContentInit
 ngAfterContentChecked
 ngAfterViewInit
 ngAfterViewChecked
 ngOnDestroy
The Different Lifecycle Hooks For Angular Components And
Directives
A lifecycle hook procedure is invoked whenever one of the properties bound is modified.
Every time the value changes, this method is invoked. The method returns a
SimpleChanges object with the property's initial and current values. In other words, the
lifecycle hook ngOnChanges() is called any time an input property of the component is
altered.

As of this writing, there are no changes to the nonchanges () function. For example,
consider the following: use changedvals[propName] to update c.

previous = previousValue; current =


JSON.stringify(c).currentValue; and
this.changeLog.push($propName: currentValue = $current,
previousValue = $previous);

Copy Code
For more in-depth info you can enroll your name in a course after knowing the web
development course price .

ngOnInit()
The function is invoked immediately after the ngOnChanges() method and the constructor.
Lifecycle hook for the component/initialization. directive's It's vital to note that
ngOnChanges() always runs before ngOnInit() in this example ().

Hooks that identify the initialization of a newly formed component are the most significant
in Angular. It is crucial to note that this hook collects data from servers and APIs, even
though it is only called once during lifecycle hooks angular rendering.

ngOnInit(){this.logIt(``);}ngDoCheck()

Copy Code
ngDoCheck is a lifecycle hook for Angular that detects changes in the application's state
(). This is called after ngOnInit() and ngOnChanges() each time a change is detected or
performed.

Developers may do manual data checks using the ngDoCheck() hook. Conditionally, it
may be used to set a new application deadline. Developers may write their tests for change
detection using "ChangeDetectorRef."

This.changeLog.push('DoCheck: Value changed to "$this.val'


from "$this.oldval'"); this.oldval = this.val;
this.changeDetected = false; this.oldval = this.val;

Copy Code
ngAfterContentInit()

When a material is projected into the component's view, this angular lifecycle hook is
activated. Once all the bindings of the components have been verified, this one is called.

During the component's lifecycle execution and after the initial ngDoCheck() hook, this
lifecycle hook is invoked once. Using this hook, we may access the "ElementRef" of the
content child's "ContentChild()" right after the component's instantiation, together with the
projected external content.

ngAfterContentChecked()
Invoked after ngAfterContentInit() and the following ngDoCheck(), this lifecycle hook
reacts to the content projection process's check of the component's content after it has been
checked. When a response is received, the hook method is always invoked.

contentChild: ChildComponent; ngAfterContentInit()


this.logIt("); @ContentChild: ChildComponent

this.logIt('Checked with no change'); else, this.val =


this.contentChild.val; this.logIt('Checked');
ngAfterContentChecked()

Copy Code
ngAfterViewInit()

These two functions are called after ngAfterContentChecked() has checked all of the
component bindings (). Angular also initializes component views and child views in this
response hook function. Components, not directives, are affected by this rule.

The lifecycle hook invoked after all of the Angular component's view has been fully
initialized is known as the "Angular AfterViewInit" hook and is part of the
"AfterViewInit" interface. For any last-minute additions to the initialization process, the
ngAfterViewInit() method is there to help.

ngAfterViewChecked()

Every time Angular checks the component views and the child view, a response hook
function is triggered. It occurs even if there is no modification or update. Only the
components are affected by this rule. After ngAfterViewInit() and every subsequent
ngAfterContentChecked(), this function is called ().

This class exports the AfterViewComponent, which implements AfterViewChecked and


AfterViewInit, as well as viewChild: ChildComponent. ngAfterViewChecked(). In the
event that this.val is not equal to the value of the corresponding viewChild's value, then
this.logIt("AfterViewChecked") is called.

ngOnDestroy()
Angular is responsible for deleting a component when it reaches the end of its lifecycle.
Before the component/directive may be destroyed, several crucial detachment processes
must be completed. ngOnDestroy() is the lifecycle hook function that performs these
actions.

If an application component is going to be deleted from the view or DOM structure, the
hook "ngOnDestroy()" will be called. Any neglected ends may be wiped off before a
component's removal from the DOM.

Angular uses this function just before destroying the component or directive. The
following are some of the functions this method performs:

 Unsubscribe Observables should be removed from the system.


 To prevent a memory leak, detach Event Handlers
 Put an end to the timers.
 Re-enable Callbacks

OnDestroy(); this.logIt(");

Constructor

Copy Code
 The constructor is the first method to be called when a class is created.
 A class's constructor guarantees that all of its fields (also known as class members)
are set to their default values.
 Analysis of constructor parameters by Angular-Dependency Injector (DI)
 A new class instance is created when a new MyClass() is called.
 Our class's constructor must be called with a specific argument type when we use a
new MyClass(), for example, the latest version of MyClass (arg1:number, arg2:string,
args: any)
 Arguments 1 and 2 must be of the same type as those specified in the constructor of
class MyClass, and argN could be anything.
How to Use Lifecycle Hooks
Hooks may be imported

 Make a statement about this element/directive. Hooks into the lifespan of a process
 Create a way to hook up
 ngOnInit is implemented with a simple component that we'll create.
 Angular CLI may be used to create an Angular project. Activate the app component
Hook interfaces may be imported from the main module. Angular lifecycle hooks name
without ng is the name of the interface. OnInit is an example of a hook interface for
ngOnInit.

Implements the lifecycle hook interface for the component

The next step is to provide the AppComponent to implement the OnInit API.

Create a way for hooking up.

Using the same name as the hook is required for all life cycle hook techniques.

import '@angular/core' from


'Component,OnInit';@Component({'app-root' is the
selector.""""""""This is the 'h2>Life Cycle
Hook'App.component.css styleUrl})

Copy Code
In other words, constructor()
console.log("AppComponent:Constructor");}onInit() of
ngOnconsole.log("AppComponent:OnInit");}}

Copy Code
Open the developer console and execute the code. The following is what you'll see. It's
important to note that the constructor event occurs before the OnInit hook.

The Order of Execution of Life Cycle Hooks

The hooks are executed in the following sequence by Angular:

 On the Creation of Components


 changes
 OnInit
 check
 AfterContentInit
 AfterContentChecked
 AfterViewInit
 AfterViewChecked
At this point, you'll see the Component with Child Component.

 OnChanges
 OnInit
 DoCheck
 AfterContentInit
 AfterContentChecked
 OnChanges -> Child Component
 OnInit of the Child Component
 DoCheck in Child Component
 AfterContentInit -> Child Component
 AfterContentChecked -> Child Component
 AfterViewInit -> Child Component
 After View Checked -> Child Component
 AfterViewInit
 AfterViewChecked
After creating the component
 changes
 check
 AfterContentChecked
 AfterViewChecked
When an input property in a component changes, the OnChanges hook is triggered, in any
other case, it won't ever go off.

Angular Lifecycle Hook Example

Here is angular lifecycle hooks example:

ChangeDetectionStrategy, Component, and Version are all imported from


"@angular/core."@Component({My app
selectorchangeDetection:ChangeDetectionStrategy.Default,""""""""

It's a good idea to use Angular Life Cycle Hooks.

This is the root component.

In other words, in other words, in other


words.<inputtype="text"name="message"[(ngModel)]="message"autocomplete="off"/>To
put it another way, br
/><inputtype="text"name="content"[(ngModel)]="content"autocomplete="off"/>

To put it another way,

obfuscate the existence of the


child:<inputtype="checkbox"name="hideChild"[(ngModel)]="hideChild"autocomplete="o
ff"/>

In other words,

App-child [message] "message" *ngIf="!hideCld">It's time to


inject some content.content /b> is shown in bold.</app-
child>})AppComponent's class is exported.name = "angular" +
version.major;to be read as "Hello""Hello" is the
content;hideChild=false;

Copy Code
In other words, constructor()

console.log("AppComponent:Contructed");}onChanges() of nuget
packageconsole.log("AppComponent:ngOnChanges");}onInit() of
ngOnconsole.log("AppComponent:ngOnInit")}ngCheck()console.log(
"AppComponent:DoCheck");}A call to
ngAfterContentInit()console.log("AppComponent:ngAfterContentIn
it");}A function called
ngAfterContentChecked()console.log("AppComponent:AfterContentC
hecked");}

Copy Code
This function is called when the view has been initialized.

console.log("AppComponent:AfterViewInit");}ngAfterViewChecked(
)'sconsole.log("AppComponent:AfterViewChecked");}onDestroy()
of a nodeconsole.log("AppComponent:ngOnDestroy");}}

Copy Code
All hooks are being monitored and logged to the console. The message and content fields
are separate. The kid component receives both properties to be used as an input, and a
property to be projected as content

The ChildComponent may be added or removed from the DOM using the hideChild form
parameter. The ngIf directive is in use here.

Unlock the Power of Python: Master the Language with our Certification Course for
Python. Start your journey today and become a Python pro! Enroll now.

Conclusion
Applications using Angular's lifecycle hook methods initialize new instances as and when
needed, initiate change detection strategies as needed, respond appropriately to updates
during any change detection, and finally perform deep cleanup before deleting specific
instances lifecycle hook methods.

Angularjs lifecycle hooks methods have been used in this article to explain what a
component lifecycle is and how it works. This is further shown how components and
directives, especially components, use the lifecycle hooks in the order in which they are
called. The KnowledgeHut’s angular training course teaches you how to construct
applications utilizing web API ASP.NET MVC5 and node.js from start to finish. This
article addressed all of the necessary hooking techniques.

Frequently Asked Questions (FAQs)

1. How many life cycle hooks are there in Angular?


Hooks are provided by Angular to enable us to monitor and respond to the events that
occur in the lifecycle of our components.
2. Which is the example of life cycle hooks?
Hooks are nothing more than callback functions that angular executes when an event
happens in the component's life cycle. For instance, ngOnInit is called when Angular
initially initializes a component. A call to ngOnChanges is made whenever an input
property of an Angular component changes.
3. What is component lifecycle in Angular?
Angular itself manages the lifespan of a component. Creation, rendering, and data-bound
properties are all handled by Angular's framework. Aside from that, it provides hooks for
responding to significant events in the lifecycle.
4. How do you add a lifecycle hook?
 Select the Auto Scaling group and then click the checkbox next to it. The Auto
Scaling groups page has a split window at the bottom
 In the Lifecycle hooks section of the Instance Management page, choose Create
lifecycle hook.
 Do the following to create a lifecycle hook
 Select Create from the drop-down menu
5. What are lifecycle hooks and why are they important?
Implement one or more of the lifecycle hook interfaces in the Angular core library to
handle events that occur throughout the lifespan of a component or directive. As Angular
builds, changes, or kills a component or directive instance using the hooks, you have the
chance to take action.

6. What are lifecycle hooks in react?


Hooks allow functional components to effectively implement state and lifecycle functions,
which are the foundations of every React application. Because they don't work within
classes, hooks let you access state and other React capabilities without building a class.

You might also like