Exploring the Angular Component Lifecycle
Amila Thennakoon
Technical Lead (Angular, Typescript, Bootstrap, CSS, and ASP.NETcore) | Agile Practitioner | Member of PMI USA | Oil and Gas
Welcome to the first issue of the NGX - LK newsletter. In this edition, we are going to talk about the various stages of the Angular component life cycle and its lifecycle hooks.
What is Angular Component
The Angular component is the main building block of the Angular application. When you building or if you are willing to start building an Angular application you should start developing with the Angular component.
The angular component mainly consists of 3 files which are
basically, all these three files are needed for an Angular component to function properly. Depending on the requirement, the user can add Angular service files and unit testing files, etc ater.
Sample Angular component
import { Component } from '@angular/core'
@Component({
selector: 'app-example', // The component's selector to use it in HTML: <app-example></app-example>
templateUrl: './example.component.html', // The path to the template file
styleUrls: ['./example.component.css'] // The styles associated with the component
})
export class ExampleComponent {
// Component's properties
message: string = 'Hello, Angular!';
// Component's methods
showMessage() {
alert(this.message);
}
};
2. HTML Template file:- example.component.html
<!-- example.component.html --
<div>
<h1>{{ message }}</h1>
<button (click)="showMessage()">Click me!</button>
</div>>
So why do We need to know about the component lifecycle?
In Angular, components have a lifecycle that defines the various stages they go through during their existence. Understanding the component lifecycle is essential for managing the behavior and state of components effectively.
The Angular component lifecycle event and hook
Each lifecycle event of the Angular component has its related lifecycle hook method
领英推荐
As an example see below demonstration
The lifecycle hooks provided by Angular allow you to hook into these event stages and execute custom code as needed. Here are the main lifecycle hooks available in Angular
Keep in mind that not all hooks are always used in every component. The lifecycle hooks you implement will depend on the specific requirements of your component. Understanding these lifecycle hooks helps you manage the component's behavior and resources effectively throughout its lifecycle.
Practical Demonstration
I have created a sample Angular project to demonstrate the how component life cycle works. Please check out the below git hub repository and clone it to you pc .
The code below prints output in the browser console when each lifecycle hook is called.
I believe you have got an idea about how Angular component life cycle hooks work.