Component Lifecycle in Angular
Last Updated :
31 Jul, 2024
In Angular, Components are the fundamental building blocks of an application. Understanding the lifecycle of these components is crucial for effective Angular Development. Angular provides several lifecycle hooks that allow developers to tap into key moments in a Component’s lifecycle and execute custom logic during those times.
Component Lifecycle Stages
The component lifecycle in Angular consists of several stages:
- Creation: The component is instantiated and its dependencies are injected.
- Change Detection: Angular checks for changes in the data-bound properties.
- Rendering: The component's template is rendered or updated.
- Destruction: The component is destroyed and cleaned up.
Lifecycle Hooks
Angular provides a set of lifecycle hooks that allow developers to execute code at specific stages of a component’s lifecycle.
1. ngOnChanges
It is called before ngOnInit (if the component has bound inputs) and whenever one or more data-bound input properties change. It is used to respond to changes in input properties.
ngOnChanges(changes: SimpleChanges) {
console.log('Changes detected:', changes);
}
2. ngOnInit
It is Called once, after the first ngOnChanges. It is used to initialize the component after Angular first displays the data-bound properties.
ngOnInit() {
console.log('Component initialized');
}
3. ngDoCheck
It is called during every change detection run, immediately after ngOnChanges and ngOnInit. It is used to detect and act upon changes that Angular can't or won't detect on its own.
ngDoCheck() {
console.log('Custom change detection');
}
4. ngAfterContentInit
It is called once after the first ngDoCheck. It is used to perform any additional initialization required for the content.
ngAfterContentInit() {
console.log('Content initialized');
}
5. ngAfterContentChecked
It is called after ngAfterContentInit and every subsequent ngDoCheck. It is used to act upon any changes after the content has been checked.
ngAfterContentChecked() {
console.log('Content checked');
}
6. ngAfterViewInit
It is called once after the first ngAfterContentChecked. It is used to perform additional initialization required for the view.
ngAfterViewInit() {
console.log('View initialized');
}
7. ngAfterViewChecked
It is called after ngAfterViewInit and every subsequent ngAfterContentChecked. It is used to act upon any changes after the view has been checked.
ngAfterViewChecked() {
console.log('View checked');
}
8. ngOnDestroy
It is called immediately before Angular destroys the component. It is used to clean up any resources, such as subscriptions and event handlers, to avoid memory leaks.
ngOnDestroy() {
console.log('Component destroyed');
}
Step-by-Step Guide to Create a Standalone Angular Component
Step 1: Install Angular CLI
Ensure you have Node.js installed. Then, install Angular CLI globally:
npm install -g @angular/cli
Step 2: Create a New Angular Project
Create a new Angular project:
ng new angular-gfg
cd angular-gfg
Step 3: Generate a Standalone Component
Generate a new standalone component called user-profile:
ng generate component user-profile --standalone
Folder Structure
Folder StructureDependencies
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Step 4: Implement Lifecycle Hooks in UserProfileComponent
HTML
<!--src/app/user-profile/user-profile.component.html-->
<div *ngIf="user">
<h2>{{ user.name }}</h2>
<p>{{ user.email }}</p>
</div>
JavaScript
//src/app/user-profile/user-profile.component.ts
import { Component, OnInit, OnChanges, DoCheck,
AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked,
OnDestroy, Input, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css'],
standalone: true,
imports: [CommonModule]
})
export class UserProfileComponent implements OnInit,
OnChanges, DoCheck, AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked, OnDestroy {
@Input() userId: string = '';
user: any;
constructor() { }
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges', changes);
}
ngOnInit() {
console.log('ngOnInit');
// Simulate fetching user data
this.user = { name: 'John Doe', email: '[email protected]' };
}
ngDoCheck() {
console.log('ngDoCheck');
}
ngAfterContentInit() {
console.log('ngAfterContentInit');
}
ngAfterContentChecked() {
console.log('ngAfterContentChecked');
}
ngAfterViewInit() {
console.log('ngAfterViewInit');
}
ngAfterViewChecked() {
console.log('ngAfterViewChecked');
}
ngOnDestroy() {
console.log('ngOnDestroy');
}
}
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { UserProfileComponent } from './user-profile/user-profile.component';
@Component({
selector: 'app-root',
template: `<app-user-profile [userId]="'1'"></app-user-profile>`,
standalone: true,
imports: [UserProfileComponent]
})
export class AppComponent { }
Step 5: Run the Application
Run the application to see the lifecycle hooks in action:
ng serve
Open your browser and navigate to http://localhost:4200. You should see the component displayed along with the console logs showing the lifecycle hook calls.
Output
Component Lifecycle in Angular
Similar Reads
Angular PrimeNG Timeline Component Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use the Timeline Component in Angular PrimeNG. We will also learn a
5 min read
Components in Angular 8 The component is the basic building block of Angular. It has a selector, template, style, and other properties, and it specifies the metadata required to process the component. Creating a Component in Angular 8: To create a component in any angular application, follow the below steps: Get to the ang
2 min read
Standalone Components In Angular In Angular, standalone components are a new feature that allows you to create components without the need for a module. This can simplify your application structure and reduce boilerplate code. This article will guide you through the concept of standalone components, including different approaches,
4 min read
ng-content in Angular The ng-content is used when we want to insert the content dynamically inside the component that helps to increase component reusability. Using ng-content we can pass content inside the component selector and when angular parses that content that appears at the place of ng-content. Syntax:Â <ng-co
2 min read
Angular Components Overview Angular Components are the building blocks of Angular applications, containing the template, styles, and behavior of a part of the user interface. This article provides an overview of Angular components, including their structure, features, and how to create and use them effectively. Table of Conten
6 min read
Angular 7 | Components Components in angular are similar to pages in a website. Components are a key feature in angular. They are well optimized as compared to pages because they are lightweight and reusable in nature. Creating a Component in angular 7: To create a component in any angular application, the first step is t
2 min read
Angular ng Bootstrap Timepicker Component Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article, we will know how to use Timepicker in angular ng bootstrap. Installation syntax: ng add @ng-bootstr
2 min read
What is entryComponents in angular ngModule ? The entryComponent is the component which loads angular by force, that means these components are not referenced in the HTML template. In most of the cases, Angular loads a component when it is explicitly declared in the component template. But this is not the case with entryComponents. The entryCom
3 min read
Handle User Events in Angular Components User events are very important for creating interactive and responsive applications in Angular. These events allow users to interact with the user interface (UI) elements, and Angular provides a convenient way to handle these events within components. In Angular, user events can be handled using eve
3 min read
Angular PrimeNG ProgressSpinner Component Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the ProgressSpinner component in Angular PrimeNG. We will a
3 min read