Understanding ngOnChanges in Angular: Detecting Input Changes from Parent Components

Understanding Angular ngOnChanges Lifecycle Hook

🔁 Understanding ngOnChanges in Angular

What Is ngOnChanges?

The ngOnChanges() method is called whenever an @Input() property changes. It receives a SimpleChanges object with previous and current values of changed inputs.

Common Use Cases

  • Reacting to Input Changes: Trigger data fetches or logic on input update.
  • Resetting Component State: Reset forms or flags based on input.
  • Comparing Old/New Values: Useful for logging or validations.
  • Conditional API/UI Updates: Perform side effects when certain inputs change.
  • Cascading Inputs: E.g., update states dropdown when country changes.

Example: Reacting to Input Change

@Input() userId!: number;

ngOnChanges(changes: SimpleChanges) {
  if (changes['userId']) {
    this.loadUserData(this.userId);
  }
}

Example: Resetting State

@Input() resetFormTrigger!: boolean;

ngOnChanges(changes: SimpleChanges) {
  if (changes['resetFormTrigger'] && this.resetFormTrigger) {
    this.form.reset();
  }
}

Full Parent → Child Example

Parent Component

// parent.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    

Parent Component

` }) export class ParentComponent { userName = 'John'; changeUser() { this.userName += '!'; } }

Child Component

// child.component.ts
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    

Child Component

Current: {{ name }}

Previous: {{ previousName }}

` }) export class ChildComponent implements OnChanges { @Input() name = ''; previousName: string | null = null; ngOnChanges(changes: SimpleChanges) { const ch = changes['name']; if (ch) { this.previousName = ch.previousValue; console.log(`Name changed: ${ch.previousValue} → ${ch.currentValue}`); } } }

Handling Nested Objects

Angular triggers ngOnChanges only when input references change. For nested object updates (e.g., user.name = 'X'), mutate the object reference in the parent:

@Input() user!: { name: string; age: number };

ngOnChanges(changes: SimpleChanges) {
  if (changes['user']) {
    console.log('User changed:', changes['user'].previousValue, '→', changes['user'].currentValue);
  }
}
💡 Tip: Use immutable update this.user = { ...this.user } in the parent to force detection.

🧠 Summary

Use Case Description
React to data changes Fetch data or logic on input change
Reset child state Clear forms or flags on trigger
Compare old vs new Useful for logs or conditional behavior
Chain logic/UI updates Handle dependent behavior or API calls
Handle nested objects Requires reference change to detect updates

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