ngOnChanges

Angular ngOnChanges & ngDoCheck with KeyValueDiffer

๐Ÿ”„ Angular Lifecycle: ngOnChanges & Change Detection

ngOnChanges

ngOnChanges fires whenever an @Input() property changes—even before the first rendering.

Common Use Cases

  • React to input changes (e.g., fetch new data)
  • Reset internal state
  • Log previous vs current values
  • Trigger conditional API calls
  • Cascading logic (like dropdown updates)

Example

@Input() name!: string;

ngOnChanges(changes: SimpleChanges) {
  const change = changes['name'];
  console.log(`Name changed from ${change.previousValue} → ${change.currentValue}`);
}

ngDoCheck & KeyValueDiffer

By default, ngOnChanges won't detect nested object changes:

this.user.name = 'New'; // no ngOnChanges triggered

Solution: use ngDoCheck with KeyValueDiffer:

@Input() user!: any;
private userDiffer!: KeyValueDiffer;

constructor(private kvDiffers: KeyValueDiffers) {}

ngOnInit() {
  this.userDiffer = this.kvDiffers.find(this.user).create();
}

ngDoCheck() {
  const changes = this.userDiffer.diff(this.user);
  if (changes) {
    changes.forEachChangedItem(r => 
      console.log(`Changed ${r.key}: ${r.previousValue} → ${r.currentValue}`)
    );
  }
}
๐Ÿ’ก Use KeyValueDiffer for detecting deep object changes; use IterableDiffer for arrays.

Best Practices

  • ✅ Use immutable data patterns to simplify change detection
  • ✅ Prefer ngOnChanges for primitive inputs
  • ❌ Reserve ngDoCheck for complex structures (watch the performance!)

๐Ÿงพ Conclusion

Use ngOnChanges for standard @Input changes and simple logic. For detecting deep mutations, leverage ngDoCheck with a differ—but only when absolutely necessary.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features