Lifecycle Hooks – Angular

Angular lifecycle hooks are special methods that allow you to tap into the lifecycle of Angular components and directives. They provide a way to execute code at specific points in a component’s lifecycle, such as when it is created, updated, or destroyed. Here’s a breakdown of some common hooks with examples:

Common Angular Lifecycle Hooks

  1. ngOnInit
  • Called once after the first ngOnChanges. It’s typically used for initialization logic.
   import { Component, OnInit } from '@angular/core';

   @Component({
     selector: 'app-example',
     template: '<h1>{{ title }}</h1>'
   })
   export class ExampleComponent implements OnInit {
     title: string;

     ngOnInit() {
       this.title = 'Hello, Angular!';
     }
   }
  1. ngOnChanges
  • Called before ngOnInit and whenever one or more data-bound input properties change. It receives a SimpleChanges object.
   import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

   @Component({
     selector: 'app-input-example',
     template: '<p>{{ data }}</p>'
   })
   export class InputExampleComponent implements OnChanges {
     @Input() data: string;

     ngOnChanges(changes: SimpleChanges) {
       console.log('Data changed:', changes.data);
     }
   }
  1. ngDoCheck
  • Called during every change detection run, and allows you to implement your own change detection.
   import { Component, DoCheck } from '@angular/core';

   @Component({
     selector: 'app-do-check-example',
     template: '<p>Check the console for changes!</p>'
   })
   export class DoCheckExampleComponent implements DoCheck {
     data: number = 0;

     ngDoCheck() {
       console.log('Change detection run:', this.data);
     }
   }
  1. ngAfterViewInit
  • Called after Angular has fully initialized a component’s view. This is a good place to interact with child components.
   import { Component, AfterViewInit, ViewChild } from '@angular/core';
   import { ChildComponent } from './child.component';

   @Component({
     selector: 'app-parent',
     template: '<app-child></app-child>'
   })
   export class ParentComponent implements AfterViewInit {
     @ViewChild(ChildComponent) child: ChildComponent;

     ngAfterViewInit() {
       console.log('Child component:', this.child);
     }
   }
  1. ngOnDestroy
  • Called just before Angular destroys the directive/component. It’s a good place to clean up subscriptions and detach event handlers.
   import { Component, OnDestroy } from '@angular/core';
   import { Subscription } from 'rxjs';

   @Component({
     selector: 'app-destroy-example',
     template: '<p>Check console for unsubscribe message</p>'
   })
   export class DestroyExampleComponent implements OnDestroy {
     private subscription: Subscription;

     constructor() {
       this.subscription = someObservable.subscribe();
     }

     ngOnDestroy() {
       this.subscription.unsubscribe();
       console.log('Subscription unsubscribed!');
     }
   }

Summary of Hooks

HookWhen It Is Called
ngOnChangesBefore ngOnInit and on input property changes
ngOnInitAfter the component is created and initialized
ngDoCheckOn every change detection cycle
ngAfterViewInitAfter the component’s view is initialized
ngOnDestroyBefore the component is destroyed

These hooks allow you to manage the lifecycle of your components effectively, enabling better resource management and responsiveness to data changes.

Tags: No tags

Add a Comment

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