Angular provides several lifecycle hooks that can be implemented in a component:
Hook | Purpose |
---|---|
ngOnInit() |
Called after the component is initialized. |
ngOnChanges() |
Called when input properties change. |
ngDoCheck() |
Detects changes manually. |
ngAfterContentInit() |
Called after content (ng-content) is projected. |
ngAfterContentChecked() |
Called after the projected content is checked. |
ngAfterViewInit() |
Called after the component’s view is initialized. |
ngAfterViewChecked() |
Called after the component’s view is checked. |
ngOnDestroy() |
Called just before the component is destroyed. |
Run the following command to generate a new component:
ng generate component lifecycle-demo
Modify the lifecycle-demo.component.ts
file:
import { Component, OnInit, OnChanges, DoCheck, AfterViewInit, OnDestroy, Input } from '@angular/core';
@Component({
selector: 'app-lifecycle-demo',
template: `<p>Lifecycle Hooks Demo</p>`,
})
export class LifecycleDemoComponent implements OnInit, OnChanges, DoCheck, AfterViewInit, OnDestroy {
@Input() data: string = '';
constructor() {
console.log('Constructor called');
}
ngOnChanges() {
console.log('ngOnChanges called - Input property changed');
}
ngOnInit() {
console.log('ngOnInit called - Component initialized');
}
ngDoCheck() {
console.log('ngDoCheck called - Change detection running');
}
ngAfterViewInit() {
console.log('ngAfterViewInit called - View initialized');
}
ngOnDestroy() {
console.log('ngOnDestroy called - Component about to be destroyed');
}
}
Modify app.component.html
:
<app-lifecycle-demo [data]="'Hello Angular'"></app-lifecycle-demo>
Run the application using:
ng serve
Understanding Lifecycle Hooks is crucial for managing component behavior at different stages. Hooks like ngOnInit
help with initialization, while ngOnDestroy
is useful for cleanup operations. By using these hooks efficiently, you can create optimized, maintainable, and performant Angular applications. 🚀