Angular components have a well-defined lifecycle, from creation to destruction. Angular provides lifecycle hooks that allow you to tap into key moments in this lifecycle and execute custom logic. These hooks are essential for managing resources, responding to changes, and optimizing performance. In this article, we’ll explore the different lifecycle hooks available in Angular, how they work, and when to use them. By the end of this guide, you’ll have a solid understanding of Angular’s component lifecycle and how to leverage it effectively.
What are Lifecycle Hooks?
Lifecycle hooks are methods that Angular calls at specific stages of a component’s lifecycle. They allow you to perform actions such as initializing data, responding to changes, and cleaning up resources. Angular provides several lifecycle hooks, each corresponding to a specific phase in the component’s lifecycle.
Angular Component Lifecycle Hooks
Here are the key lifecycle hooks available in Angular:
- ngOnChanges: Called when an input property changes.
- ngOnInit: Called after the component is initialized.
- ngDoCheck: Called during every change detection cycle.
- ngAfterContentInit: Called after content is projected into the component.
- 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 before the component is destroyed.
Using Lifecycle Hooks
Let’s explore each lifecycle hook in detail and see how to use them in your components.
1. ngOnChanges
The ngOnChanges
hook is called whenever an input property changes. It receives a SimpleChanges
object that contains the current and previous values of the input properties.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>{{ message }}</p>`,
})
export class ChildComponent implements OnChanges {
@Input() message: string;
ngOnChanges(changes: SimpleChanges) {
console.log('Input changed:', changes);
}
}
2. ngOnInit
The ngOnInit
hook is called after the component is initialized. It’s a good place to perform initialization logic, such as fetching data from a server.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>{{ message }}</p>`,
})
export class AppComponent implements OnInit {
message: string;
ngOnInit() {
this.message = 'Component initialized!';
}
}
3. ngDoCheck
The ngDoCheck
hook is called during every change detection cycle. It’s useful for detecting changes that Angular’s default change detection mechanism might miss.
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>{{ message }}</p>`,
})
export class AppComponent implements DoCheck {
message: string;
ngDoCheck() {
console.log('Change detection cycle');
}
}
4. ngAfterContentInit
The ngAfterContentInit
hook is called after content is projected into the component using ng-content
.
import { Component, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `<ng-content></ng-content>`,
})
export class ParentComponent implements AfterContentInit {
ngAfterContentInit() {
console.log('Content projected');
}
}
5. ngAfterContentChecked
The ngAfterContentChecked
hook is called after the projected content is checked during the change detection cycle.
import { Component, AfterContentChecked } from '@angular/core';
@Component({
selector: 'app-parent',
template: `<ng-content></ng-content>`,
})
export class ParentComponent implements AfterContentChecked {
ngAfterContentChecked() {
console.log('Content checked');
}
}
6. ngAfterViewInit
The ngAfterViewInit
hook is called after the component’s view is initialized. It’s a good place to interact with the DOM or child components.
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p #message>Hello</p>`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('message') messageElement: ElementRef;
ngAfterViewInit() {
console.log('View initialized:', this.messageElement.nativeElement.textContent);
}
}
7. ngAfterViewChecked
The ngAfterViewChecked
hook is called after the component’s view is checked during the change detection cycle.
import { Component, AfterViewChecked } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>{{ message }}</p>`,
})
export class AppComponent implements AfterViewChecked {
message: string;
ngAfterViewChecked() {
console.log('View checked');
}
}
8. ngOnDestroy
The ngOnDestroy
hook is called before the component is destroyed. It’s a good place to clean up resources, such as unsubscribing from observables.
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-root',
template: `<p>{{ message }}</p>`,
})
export class AppComponent implements OnDestroy {
message: string;
private subscription: Subscription;
ngOnDestroy() {
this.subscription.unsubscribe();
console.log('Component destroyed');
}
}
Secrets and Hidden Facts
- Order of Execution: Lifecycle hooks are called in a specific order. For example,
ngOnInit
is called afterngOnChanges
. - Performance Considerations: Be cautious when using hooks like
ngDoCheck
andngAfterViewChecked
, as they can impact performance if overused. - Custom Change Detection: Use
ngDoCheck
to implement custom change detection logic.
Conclusion
Angular’s component lifecycle hooks provide a powerful way to manage the lifecycle of your components. By understanding and leveraging these hooks, you can perform initialization, respond to changes, and clean up resources effectively. Whether you’re building a simple component or a complex one, lifecycle hooks are an essential tool for Angular development.
So, start using lifecycle hooks in your projects and unlock the full potential of Angular!

No comments: