ngOnChanges Example | Angular

Last modified: April 22, 2019

ngOnChanges Example

ngOnInit Example

ngDoCheck Example

ngAfterContentInit Example

ngAfterContentChecked Example

ngAfterViewInit Example

ngAfterViewChecked Example

ngOnDestroy Example

child.component.ts

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

@Component({
  selector: 'app-child',
  template: `
    <a (click)="changeFromChild()">Change from child</a>
    <br/>
    {{parentData}}
  `
})
export class ChildComponent implements OnInit {
  @Input() parentData: any;
  constructor() {
  }

  ngOnInit() {
  }

  changeFromChild(){
    this.parentData -= 1;
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes)
  }
}

parent.component.ts

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

@Component({
  selector: 'app-parent',
  template: `
    <a (click)="changeFromParent()">Change from parent</a>
    <br/>
    <app-child [parentData]=data></app-child>
  `
})
export class ParentComponent implements OnInit {
  data = 0
  constructor() {
  }

  ngOnInit() {
  }

  changeFromParent(){
    this.data += 1;
  }
}

ngOnChanges() will fire before ngOnInit() and every time parentDatais updated from its parent component.

ngOnChanges() takes a changes argument of type SimpleChanges.

changeFromChild() won't call ngOnChanges()

changeFromParent() will call ngOnChanges()

When ngOnChanges() is called, this example simply logs the SimpleChanges instance.

The SimpleChanges instance looks like this...

class SimpleChange {
  constructor(previousValue: any, currentValue: any, firstChange: boolean)
  previousValue: any
  currentValue: any
  firstChange: boolean
  isFirstChange(): boolean
}

Every time ngOnChanges() is called, the SimpleChanges instance captures the parentData's:

  • previousValue
  • currentValue
  • firstChange (true the first time ngOnChanges is called)

When should you use ngOnChanges?

Use ngOnChanges whenever you want to detect changes from a variable decorated by @Input. Remember that only changes from the parent component will trigger this function.

Also remember that changes from the parent still update the child value even without implementing ngOnChanges. ngOnChanges simply adds the benefit of tracking those changes with previous and current value.

What about multiple inputs?

Each bound variable is returned with its corresponding SimpleChanges instance in a single object.

You might also like: