skip to content
Alvin Lucillo

Track changes with ngOnChange

/ 2 min read

💻 Tech

ngOnChanges hook method can be used to track any changes to the input variables declared with @Input decorator. Note that this is also triggered when you initialize component properties. Below are the parent and child components. Parent component’s initial defaultData is ‘hello’ but later changed to ‘hi’ when the button is clicked. Child component tracks these changes with ngOnChanges hook method.

This is the SimpleChanges data during page load. currentValue is the new change captured by the hook, previousValue is the value before the it’s replaced, and firstChange indicates if it’s the initial change.

{
    "inputData": {
        "previousValue": undefined,
        "currentValue": "hello",
        "firstChange": true
    }
}

This is the SimpleChanges data after the button is clicked and new value is assigned to greetings.

{
    "inputData": {
        "previousValue": "hello",
        "currentValue": "hi",
        "firstChange": false
    }
}

Component source code:

<p>parent works!</p>
<input type="button" value="change input" (click)="buttonclick($event)" />

<app-child [inputData]="greetings"></app-child>
import { Component } from '@angular/core';
import { ChildComponent } from '../child/child.component';

@Component({
  selector: 'app-parent',
  standalone: true,
  imports: [ChildComponent],
  templateUrl: './parent.component.html',
  styleUrl: './parent.component.css',
})
export class ParentComponent {
  constructor() {}

  greetings: string = 'hello';

  public buttonclick(event: any) {
    this.greetings = 'hi';
  }
}
<p>child works!</p>
<p>{{ inputData }}</p>
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  standalone: true,
  imports: [],
  templateUrl: './child.component.html',
  styleUrl: './child.component.css',
})
export class ChildComponent implements OnChanges {
  @Input() inputData!: string;

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