Component Lifecycle in Angular (original) (raw)
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 Structure
Dependencies
"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",0.14.3"
"tslib": "^2.3.0",
"zone.js": "
}
Step 4: Implement Lifecycle Hooks in UserProfileComponent
HTML `
{{ user.name }}
{{ user.email }}
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: 'john.doe@example.com' };
}
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