Git Tutorial

Angular Lifecycle Hooks

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:

HookPurpose
ngOnInitInitialize the component. Called once after the first ngOnChanges.
ngOnChangesRespond to changes in input properties.
ngDoCheckCustom change detection and action tracking.
ngAfterContentInitRespond after content (e.g., <ng-content>) has been projected into the component.
ngAfterContentCheckedRespond after projected content is checked by Angular.
ngAfterViewInitRespond after the component’s view (and child views) are initialized.
ngAfterViewCheckedRespond after the component’s view (and child views) have been checked by Angular.
ngOnDestroyPerform 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

1 thought on “Angular Lifecycle Hooks”

  1. Pingback: What Is Angular - Tech Mentor

Leave a Comment

Your email address will not be published. Required fields are marked *