The A to Z Guide to the Lifecycle of Angular Components
A discussion of several different Angular components, the concept of lifecycle hooks, and how component lifecycles work in Angular.
Join the DZone community and get the full member experience.
Join For FreeAngular is a prevalent, broadly used client-side platform that has won millions of developers' hearts in recent years. With the emergence of the Angular platform, application building has become easier for both web and mobile. There are new versions emerging each year and the Angular lifecycle keeps on evolving.
The platform was introduced by Google back in 2009. AngularJS, the first initiative by the Angular team, was extensively popular and was dependent on HTML and JavaScript. However, in the later versions, you'll find that JavaScript was replaced by TypeScript.
Angular has given developers the freedom to develop applications that can run on web, mobile, and desktop. With time, Angular has undergone many modifications and has introduced many versions after AngularJS, now up to Angular 7.
What Is Angular Lifecycle?
Each Angular version goes through various phases in its lifecycle. Components have a critical job in Angular; here, I will talk about the component lifecycle in Angular and how they impact the lifecycle of all versions of the framework. For smoothness in the development process, Angular manages all its components. Like any natural lifecycle, each component has its lifecycle events like birth, life events, and death.
It is interesting to notice that Angular itself oversees the lifecycle of all Angular components and directives. You have to understand the lifecycle with the result in mind in order to have smooth progress while developing your application. The following information applies to both components and directives.
Components are the primary building block for any Angular app. So one must understand them in order to understand the processing steps of the lifecycle of components. Only then can be implemented in the development of an application.
The most exciting thing that you will notice in Angular is each and every component in it has a lifecycle, and every stage of a lifecycle goes from initialization to destruction. A component lifecycle typically goes through eight different stages.
When an Angular component gets initialized, it creates and presents its root components. These are then designed and produce child components. For all of the components that get loaded during the development of the application, it keeps checking when the data binding properties are changed and updated. When the component is not utilized anymore, it is then deleted and expelled from the DOM. Sometimes you may have to write some additional code as these events take place. I have tried to present the most natural glimpse into the lifecycle of a component. Now, let us elaborate on it.
Lifecycle Hook Overview
The events in the life of a component are also referred to as “lifecycle hooks.” The term lifecycle hooks refers to simple functions that a developer can call at a specific point in the life of a component in their Angular application. We can also state that these lifecycle hooks are callback methods that Angular raises when a positive event happens in the lifecycle of a component. There are eight distinct kinds of hooks in the lifecycle of a component or directive.
You can execute hooks from the Angular core library, as well, in order to consolidate some unique components into the lifecycle of your application. Developers use significant moments of a lifecycle by actualizing one or more hook interfaces from the Angular core library. Hook events can be included at any stage of an application to get excellent control over the components.
For example, to introduce a component, ngOnInit
, is summoned by Angular.
- For the changed input property of a component,
ngOnChange
is invoked by Angular. - On the destruction of a component,
ngOnDestroy
is invoked by Angular.
The components are TypeScript classes, which is why you have to consider every component as a constructor method. In the lifecycle hook event, the constructor of the component class gets executed first. For injecting a dependency into the component, you must make use of the constructor. Angular executes the constructor first, then the execution of all other lifecycle hook methods occurs explicitly.
Constructor vs. OnInt
Being a developer, it will be essential for you to generate your component and introduce it. For that, you must settle on one of two options: you can utilize a constructor or use the OnInit
lifecycle method. With the initialization of component, the OnInit
lifecycle method gets triggered.
Which method you like to use is your decision, but many people have said that they prefer to use ngOnInit
for declaration or initialization and try not to use the constructors.
Interfaces
The interface is a fundamental instrument to hook into the lifecycle method, as the component class of your application needs to implement the essential interface. As for the introduction of a view, the method that should be triggered to implement the interface is AfterViewInit
and the method for this is ngAfterViewInit
.
ngOnchanges
This callback function is sought after when the data-bound property variations happen for a component; that is to say, this event gets executed as and when the input control gets renewed inside the component. A changed data map is received by the Angular app, containing the present and previous position of the data-bound property encased in a simple change.
Using this lifecycle hook, a parent component can easily communicate with its child component if the property decorator exposes the @InputDecorator
of the child component. Developers use this hook to discover the details about the input property that has been changed and how it got changed.
Properties:
- It can be utilized practically in all the components that have input.
- Get invoked whenever the input value gets changed.
It's called to get raised before ngOnInit
.
ngOnInit
When Angular has completed the creation and introduction of components this callback is invoked. It also gets initialized as Angular displays data-bound properties. This event gets its call only after an ngOnChanges
event and after the constructor. With this hook, you can initialize logic to your component. As this hook gets initializated after ngOnChanges
, all the properties ngOnInit
can use all of its properties. Any of the child directive properties cannot be used before this code gets triggered.
Properties:
- This hook initializes data for a component.
- After setting the input values, this hook gets its call.
- This hook is added by default by the Angular CLI to all the components.
- It is only called once.
ngDoCheck
This is most sought after hook whenever there is a need to review the input property of a component or directive. You can even use this call back to check your logic. In short, through this hook, you can do custom checks on the logic that you want to implement in the component.
This hook comes on demand instantly after ngOnInit
, and this hook is executed even if there is no change in the property of a component. This hook comes to the rescue if Angular fails to detect any change in the input property.
Properties:
- Run by Angular to detect any changes.
- Called for change detection.
ngAfterContentInit
ngAfterContentInit
is called after ngDoCheck
when tje content of the components gets introduced and checked for the first time. This method is implemented as soon as Angular makes any content projection within a component view. This method is also called when the properties get clearly demarcated as ContentChild
and ContentChildren
and are fully initialized.
External child components can be included by Angular using this method within the <ng-content> </ng-content> tag. In the total lifecycle of a component, this hook gets called once.
Properties:
- Only used after
ngDoCheck
it is called. - It does its work by initializing the content.
ngAfterContentChecked
This hook method accomplishes its work by investigating the modification in the content of the component using the Angular change detection apparatus, and it still performs its task even if there is no modification being made. It gets called after ngAftercontentInit
and also gets executed after every execution of ngDoCheck
. It plays a big role in the initialization of the child component.
Properties:
- This method waits for
ngContentInit
to finish its execution to get started. - Executed after all
ngDocheck
.
ngAfterViewInit
This lifecycle method gets its call after ngAfterContentChecked
and is only used only on components. This is very similar to ngAfterContentInit
, and it gets invoked only after all the component view and its child view.
Properties:
- After the initialization of view, it gets called only once.
ngAfterViewChecked
This Angular lifecycle method gets triggered after the checks of component’s view and child view. This method gets its call after ngAfterViewInit
and then for every ngAfterContentChecked
method. Like many other lifecycle hooks discussed above it is also applicable for components only.
When something is awaited from the child component, this component can be helpful.
Properties:
- After the checking and initialization are done, this gets its called.
- After every
ngAfterContentChecked
method finishes its job, this method starts its work.
ngOnDestroy
This lifecycle hook gets its call after Angular destroys all the components or directives. This is the place where you can use your clean up logic and unsubscribe from all observables and detach from event handlers. By doing so, you can prevent memory leakage.
Properties:
- Gets called just before components get removed from the DOM.
How Can You Make Use of Angular Lifecycle Hooks?
The steps that you should follow are:
- First, you have to import the hook interface.
- In the hook interface, you ought to announce the component or directive.
- Next, you ought to generate the hook method.
The Best Strategy to Import Hook Interfaces
Here, importing the hook interface from the core module is essential. Adding a prefix before the name is not required.
The code for this would look like:
The code is taken from https://angular.io/guide/lifecycle-hooks
export class SpyDirective implements OnInit, OnDestroy { ….}; @angular/core’;
The code is taken from https://angular.io/guide/lifecycle-hooks
Statement of the Component That Actualizes Lifecycle Hooks
In the subsequent stages, you need to characterize the app component that executes the OnInit
interface. The code structure for that is given below.
export class AppComponent { ,
syntax taken from c-sharpcorner.com
Generating the Hook Methods
One thing that you should remember is the “hook” and “hook method” must have the same name.
Right at the point when the components are made the hooks are implemented in the way depicted below:
However, the arrangement of execution gets some expansion in it when components with the child are created.
Now, for child components, we again have to run the following:
Here again, children join the parent after ViewInit
.
Conclusion
In this article, I have discussed lifecycle hooks and the sequence in which they occur in the lifecycle of a component or a directive. One thing you should remember is these lifecycle hooks apply to both components and directives.
Being a developer you must know how important components are in Angular. Being familiar these lifecycle hooks is equally important. After reading this article, I hope you have gained the knowledge about the hooks and what role they play in the lifecycle of Angular development. You should be cautious of using these hooks as all the hooks may not be needed for your project, so choose those which are necessary for you.
Published at DZone with permission of Sagar Tambe. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments