In Angular, lifecycle hooks are special methods that allow you to tap into various stages of a component or directive's life. They are called at specific points during the lifecycle of a component, giving you control over the creation, updating, and destruction phases. Understanding these hooks is crucial for managing resources, handling side effects, and optimizing performance in Angular applications.
What Are Angular Lifecycle Hooks?
Lifecycle hooks are methods in Angular that are executed at specific points in the lifecycle of a component or directive. These hooks provide opportunities to execute custom code in response to changes in the component's state, view, or input properties.
Common Angular Lifecycle Hooks
There are several lifecycle hooks available in Angular. The most commonly used ones are:
ngOnChanges()
ngOnInit()
ngDoCheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
ngOnDestroy()
1. ngOnChanges()
When it is called: It is called whenever an input property of the component changes.
Purpose: Used to respond to changes in data passed to the component through input properties (
@Input
).
Example:
typescriptCopy codeimport { Component, OnChanges, SimpleChanges, Input } from '@angular/core';
@Component({
selector: 'app-example',
template: `<p>{{ value }}</p>`
})
export class ExampleComponent implements OnChanges {
@Input() value: string;
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges:', changes);
}
}
Explanation:
ngOnChanges
is triggered whenever thevalue
input changes. TheSimpleChanges
object provides information about the changes (current and previous values).
2. ngOnInit()
When it is called: It is called once, after the component’s data-bound properties have been initialized.
Purpose: It's commonly used for initializing data or making initial API calls.
Example:
typescriptCopy codeimport { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `<p>{{ message }}</p>`
})
export class ExampleComponent implements OnInit {
message: string;
ngOnInit() {
this.message = 'Component Initialized!';
console.log('ngOnInit: Component initialized.');
}
}
Explanation:
ngOnInit
is typically used to initialize properties or to perform one-time actions (like API calls) once the component's properties are set.
3. ngDoCheck()
When it is called: It is called during every change detection cycle, even when there are no actual changes.
Purpose: This hook is useful for implementing custom change detection or responding to specific, fine-grained changes that Angular's default change detection mechanism cannot catch.
Example:
typescriptCopy codeimport { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-example',
template: `<p>{{ counter }}</p>`
})
export class ExampleComponent implements DoCheck {
counter = 0;
ngDoCheck() {
console.log('ngDoCheck: Change detection cycle running.');
}
}
Explanation:
ngDoCheck
will be triggered on every change detection cycle, making it useful for scenarios where you need to detect changes manually.
4. ngAfterContentInit()
When it is called: It is called once after Angular has fully initialized all content projected into the component (i.e., content inside
<ng-content>
).Purpose: This hook is useful when the component's content (projected content) has been fully initialized, and you need to do something with that content.
Example:
typescriptCopy codeimport { Component, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `<ng-content></ng-content>`
})
export class ExampleComponent implements AfterContentInit {
ngAfterContentInit() {
console.log('ngAfterContentInit: Content has been initialized.');
}
}
Explanation:
ngAfterContentInit
will be triggered after the content inside<ng-content>
has been fully initialized. This is particularly useful for content projection.
5. ngAfterContentChecked()
When it is called: It is called after every check of the content projected into the component (i.e., content inside
<ng-content>
).Purpose: Use this hook if you need to perform actions whenever Angular checks the projected content.
Example:
typescriptCopy codeimport { Component, AfterContentChecked } from '@angular/core';
@Component({
selector: 'app-example',
template: `<ng-content></ng-content>`
})
export class ExampleComponent implements AfterContentChecked {
ngAfterContentChecked() {
console.log('ngAfterContentChecked: Content has been checked.');
}
}
Explanation:
ngAfterContentChecked
runs after every change detection cycle where content is checked, allowing you to perform actions after each check.
6. ngAfterViewInit()
When it is called: It is called once after Angular has fully initialized the component’s view and child views.
Purpose: Use this hook for tasks that need to interact with the component's view or child views (like setting focus, initializing third-party libraries, etc.).
Example:
typescriptCopy codeimport { Component, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `<div #box></div>`
})
export class ExampleComponent implements AfterViewInit {
ngAfterViewInit() {
console.log('ngAfterViewInit: Component view and child views are initialized.');
}
}
Explanation:
ngAfterViewInit
runs once after the component's view and its child views have been fully initialized, making it ideal for DOM manipulations or interactions.
7. ngAfterViewChecked()
When it is called: It is called after every check of the component’s view and child views.
Purpose: Useful for responding to changes in the component’s view after Angular checks it.
Example:
typescriptCopy codeimport { Component, AfterViewChecked } from '@angular/core';
@Component({
selector: 'app-example',
template: `<div>{{ counter }}</div>`
})
export class ExampleComponent implements AfterViewChecked {
counter = 0;
ngAfterViewChecked() {
console.log('ngAfterViewChecked: Component view has been checked.');
}
}
Explanation:
ngAfterViewChecked
runs after every change detection cycle for the component’s view, providing the opportunity to perform actions after view updates.
8. ngOnDestroy()
When it is called: It is called just before Angular destroys the component.
Purpose: Use this hook to clean up any resources (like unsubscribing from observables or detaching event listeners) when the component is destroyed.
Example:
typescriptCopy codeimport { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-example',
template: `<p>Component will be destroyed soon.</p>`
})
export class ExampleComponent implements OnDestroy {
ngOnDestroy() {
console.log('ngOnDestroy: Component is about to be destroyed.');
}
}
Explanation:
ngOnDestroy
is useful for cleanup tasks like unsubscribing from observables, clearing timers, or detaching event listeners when the component is destroyed.
Lifecycle Hook Summary
Lifecycle Hook | When It’s Called | Purpose |
ngOnChanges() | Whenever input properties change. | Respond to changes in input properties. |
ngOnInit() | Once the component’s input properties are initialized. | Initialize data and perform one-time actions. |
ngDoCheck() | During every change detection cycle. | Custom change detection or manual checks. |
ngAfterContentInit() | After content has been projected into the component. | Initialize content-related logic. |
ngAfterContentChecked() | After content has been checked by change detection. | Respond to changes in projected content. |
ngAfterViewInit() | After the component’s view and child views are initialized. | Perform actions that require interaction with the view. |
ngAfterViewChecked() | After the component’s view and child views have been checked. | Respond to changes in the component’s view. |
ngOnDestroy() | Just before the component is destroyed. | Cleanup logic before component is destroyed. |