Component Lifecycle Hooks
Component Lifecycle Hooks
Component Lifecycle Hooks
explained
March 26, 2021 11 min read
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:
1. constructor()
2. OnChanges
3. OnInit
4. DoCheck
5. OnDestroy
1. AfterContentInit
2. AfterContentChecked
3. AfterViewInit
4. AfterViewChecked
AfterContentChecked Called when the component’s content is updated or checked for updates
AfterViewInit Called when the component’s projected view has been initialized
@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.
@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.
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:
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:
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.
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,
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.
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."
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.
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 ().
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:
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.
The next step is to provide the AppComponent to implement the OnInit API.
Using the same name as the hook is required for all life cycle hook techniques.
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.
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.
In other words,
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.