Angular lifecycle hooks allow developers to tap into specific moments in a component or directive’s lifecycle, enabling actions such as initialization, change detection, or cleanup. In this tutorial, we’ll explain each lifecycle hook and demonstrate how to use them in standalone components.
1. What Are Lifecycle Hooks?
Lifecycle hooks are methods that Angular calls at specific stages of a component or directive’s lifecycle. These hooks provide opportunities to:
- Execute logic after the component is created.
- Respond to changes in input properties.
- Clean up resources when the component is destroyed.
2. List of Lifecycle Hooks
Here’s a summary of the most commonly used hooks:
Hook | Purpose |
ngOnInit | Initialize the component. Called once after the first ngOnChanges . |
ngOnChanges | Respond to changes in input properties. |
ngDoCheck | Custom change detection and action tracking. |
ngAfterContentInit | Respond after content (e.g., <ng-content> ) has been projected into the component. |
ngAfterContentChecked | Respond after projected content is checked by Angular. |
ngAfterViewInit | Respond after the component’s view (and child views) are initialized. |
ngAfterViewChecked | Respond after the component’s view (and child views) have been checked by Angular. |
ngOnDestroy | Perform cleanup just before the component is destroyed. |
3. Creating a Standalone Component to Demonstrate Lifecycle Hooks
Let’s create a LifecycleDemoComponent
to understand these hooks.
Generate the Component:
ng generate component lifecycle-demo
4. Implementing Lifecycle Hooks
src/app/lifecycle-demo/lifecycle-demo.component.ts
:
import { Component, Input, OnChanges, OnInit, DoCheck, AfterContentInit,
AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy } from '@angular/core';
@Component({
selector: 'app-lifecycle-demo',
standalone: true,
template: `
<h1>Lifecycle Hooks Demo</h1>
<p><strong>Input Property:</strong> {{ inputProperty }}</p>
<button (click)="changeInput()">Change Input Property</button>
<div>
<ng-content></ng-content>
</div>
<p><em>Check the console for hook logs.</em></p>
`,
})
export class LifecycleDemoComponent
implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {
@Input() inputProperty: string = 'Initial Value';
constructor() {
console.log('Constructor: Component instance created.');
}
ngOnChanges(): void {
console.log('ngOnChanges: Input property changed.');
}
ngOnInit(): void {
console.log('ngOnInit: Component initialized.');
}
ngDoCheck(): void {
console.log('ngDoCheck: Change detection triggered.');
}
ngAfterContentInit(): void {
console.log('ngAfterContentInit: Content projection completed.');
}
ngAfterContentChecked(): void {
console.log('ngAfterContentChecked: Projected content checked.');
}
ngAfterViewInit(): void {
console.log('ngAfterViewInit: Component views initialized.');
}
ngAfterViewChecked(): void {
console.log('ngAfterViewChecked: Component views checked.');
}
ngOnDestroy(): void {
console.log('ngOnDestroy: Component is about to be destroyed.');
}
changeInput(): void {
this.inputProperty = 'Updated Value';
}
}
5. Using the Component
To test the lifecycle hooks, use the LifecycleDemoComponent
in the AppComponent
.
src/app/app.component.ts
:
import { Component } from '@angular/core';
import { LifecycleDemoComponent } from './lifecycle-demo/lifecycle-demo.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [LifecycleDemoComponent],
template: `
<app-lifecycle-demo [inputProperty]="dynamicValue">
<p>This is projected content!</p>
</app-lifecycle-demo>
<button (click)="destroyComponent()">Toggle Component</button>
`,
})
export class AppComponent {
dynamicValue = 'Hello, Angular!';
showComponent = true;
destroyComponent() {
this.showComponent = !this.showComponent;
}
}
6. Practical Uses of Lifecycle Hooks
ngOnInit
: Fetch initial data or set up default values.ngOnChanges
: Respond to changes in@Input
properties.ngOnDestroy
: Clean up subscriptions, clear timers, or release resources.
Summary of Logs in Console
- Component Creation:
Constructor
ngOnInit
- Change Detection:
ngOnChanges
ngDoCheck
- Content Projection:
ngAfterContentInit
ngAfterContentChecked
- View Initialization:
ngAfterViewInit
ngAfterViewChecked
- Cleanup:
ngOnDestroy
Pingback: What Is Angular - Tech Mentor