ngOnDestroy Example | Angular

ngOnChanges Example

ngOnInit Example

ngDoCheck Example

ngAfterContentInit Example

ngAfterContentChecked Example

ngAfterViewInit Example

ngAfterViewChecked Example

ngOnDestroy Example


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

  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() { }
    this.showChild = !this.showChild
  ngOnInit() {
    console.log("parent init")


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

  selector: 'app-child',
  template: `Here is the child component.`,
  // changeDetection: ChangeDetectionStrategy.OnPush
export class ChildComponent implements OnInit {
  constructor() { }
  ngOnInit() {
    console.log("child init")
    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?