0
0
Angularframework~5 mins

ngOnChanges for input changes in Angular

Choose your learning style9 modes available
Introduction

ngOnChanges helps your Angular component notice when input values change. It lets you react to those changes right away.

You want to update something inside your component when a parent sends new data.
You need to run code every time an input property changes.
You want to compare old and new input values to decide what to do next.
You want to initialize or reset some values when inputs change.
Syntax
Angular
ngOnChanges(changes: SimpleChanges): void {
  // your code here
}

ngOnChanges is a lifecycle method Angular calls automatically.

The changes object holds current and previous values of inputs.

Examples
This example checks if inputName changed and logs the new value.
Angular
ngOnChanges(changes: SimpleChanges) {
  if (changes['inputName']) {
    console.log('inputName changed:', changes['inputName'].currentValue);
  }
}
This example loops through all changed inputs and logs their old and new values.
Angular
ngOnChanges(changes: SimpleChanges) {
  for (const propName in changes) {
    const change = changes[propName];
    console.log(`${propName} changed from ${change.previousValue} to ${change.currentValue}`);
  }
}
Sample Program

This example has a parent component with a button that changes a string. The child component receives this string as input and uses ngOnChanges to log when the input changes.

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

@Component({
  selector: 'app-child',
  template: `<p>Child input: {{ data }}</p>`
})
export class ChildComponent implements OnChanges {
  @Input() data: string = '';

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['data']) {
      console.log(`data changed from '${changes['data'].previousValue}' to '${changes['data'].currentValue}'`);
    }
  }
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="changeData()">Change Data</button>
    <app-child [data]="parentData"></app-child>
  `
})
export class AppComponent {
  parentData = 'Hello';

  changeData() {
    this.parentData = this.parentData === 'Hello' ? 'World' : 'Hello';
  }
}
OutputSuccess
Important Notes

ngOnChanges runs before ngOnInit on the first input binding.

If input value does not change, ngOnChanges will not run.

Always check if the input property exists in changes before using it.

Summary

ngOnChanges lets your component react to input changes.

It receives a SimpleChanges object with old and new values.

Use it to update or reset data when inputs change.