In Angular, component lifecycle hooks are methods that provide visibility into the lifecycle events of a component. These hooks allow you to perform actions at specific moments in a component's lifecycle, such as initialization, change detection, content projection, and destruction. Here are the main lifecycle hooks available in an Angular component:
Initialization
-
ngOnChanges:
Called whenever one or more data-bound input properties change. Receives a
SimpleChanges
object containing the previous and current property values. -
ngOnInit:
Invoked once, after the first
ngOnChanges
. This hook is used for initialization logic such as fetching initial data from a service.
Content Projection (View Initialization)
- ngDoCheck: Called during every change detection cycle. Use this hook to perform your own custom change detection.
Component Interaction
-
ngAfterContentInit: Called once after the component's content has been initialized. It's used when your component depends on external content provided through
ng-content
. -
ngAfterContentChecked: Called after the
ngDoCheck
and every subsequent check of the component's content. It's useful for performing operations after Angular checks the content projected into the component. - ngAfterViewInit: Invoked once after the component's view (and child views) have been initialized. Use it for operations that require the component's view to be fully initialized.
-
ngAfterViewChecked: Called after
ngAfterContentChecked
and every subsequent check of the component's view. Use this hook for additional logic that needs to be executed after the view and its children have been checked.
Destruction
- ngOnDestroy: Invoked just before the component is destroyed. Use it for cleanup logic such as unsubscribing from observables to avoid memory leaks.
import { Component, OnInit, OnDestroy, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit, OnDestroy, OnChanges {
// Input property
@Input() data: any;
constructor() { }
ngOnInit(): void {
// Initialization logic, data fetching, etc.
}
ngOnChanges(changes: SimpleChanges): void {
// React to changes in input properties
}
ngDoCheck(): void {
// Custom change detection logic
}
ngAfterContentInit(): void {
// After component content initialization
}
ngAfterContentChecked(): void {
// After content check
}
ngAfterViewInit(): void {
// After view initialization
}
ngAfterViewChecked(): void {
// After view check
}
ngOnDestroy(): void {
// Cleanup logic
}
}
Understanding and utilizing these lifecycle hooks enables you to manage component initialization, perform specific tasks at various stages, and handle cleanup activities effectively in your Angular applications.