ngOnDestroy Example | Angular

ngOnChanges Example

ngOnInit Example

ngDoCheck Example

ngAfterContentInit Example

ngAfterContentChecked Example

ngAfterViewInit Example

ngAfterViewChecked Example

ngOnDestroy Example

parent.component.ts

import { Component, OnInit, AfterContentInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `<a (click)="update()">Update</a><br/>
              <app-child *ngIf='showChild'></app-child>`
})
export class ParentComponent implements OnInit {
  public showChild = true
  constructor() { }
  update(){
    this.showChild = !this.showChild
  }
  ngOnInit() {
    console.log("parent init")
  }
}

child.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `Here is the child component.`,
  // changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent implements OnInit {
  constructor() { }
  ngOnInit() {
    console.log("child init")
  }
  ngOnDestroy(){
    console.log("destroying child...")
  }
}

ngOnDestroy() gets called when a component is about to be destroyed.

Notice how the example "destroys" the child component via the conditional ngIf='showChild'.

By toggling the value of showChild, Angular creates and destroys the child component each time this value changes.

Every time the update() function is triggered, ngOnInit() or ngOnDestroy() is called on the child component.

When should you use ngOnDestroy?

Using ngOnDestroy makes sense when you want to implement customized behavior when a component is destroyed.

ngOnDestroy can be helpful when you need to unsubscribe from observables or perform any other clean up when destroying a component.

Your thoughts?