ngOnChanges

ngOnChanges

ngOnChanges is a lifecycle hook that is triggered whenever an @Input() property changes, including before the component is rendered the first time.

Common Use Cases:

  1. React to Input Changes: Fetch data, recalculate values, or run logic when an input changes.
  2. Reset Internal State: Clear or update internal variables based on new inputs.
  3. Track Previous vs Current Values: Useful for logs or conditional operations.
  4. Conditional API Calls: Trigger HTTP or DOM updates when inputs meet criteria.
  5. Cascading Dropdowns: Update dependent data like states based on selected country.

Example:

Parent Component:

userName = 'John';

changeName() {

  this.userName = 'Jane';

}

Child Component:

@Input() name!: string;

 

ngOnChanges(changes: SimpleChanges) {

  const change = changes['name'];

  console.log(`Name changed from ${change.previousValue} to ${change.currentValue}`);

}

 

ngDoCheck + KeyValueDiffer

Problem:

Angular’s default change detection does not catch changes inside nested object properties.

this.user.name = 'New'; // ngOnChanges will not trigger

Solution:

  1. Use ngDoCheck: Called during every change detection cycle.
  2. Use KeyValueDiffer: Detects added, removed, or modified properties in an object.

Example:

@Input() user!: any;

private userDiffer!: KeyValueDiffer<string, any>;

 

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}`)

    );

  }

}

 

Best Practices:

  • Use KeyValueDiffer for complex or deeply nested objects.
  • For arrays, prefer IterableDiffer.
  • Use immutable patterns where possible for simpler change detection.
  • Use ngDoCheck only when required due to potential performance costs.

 

 

Comments

Popular posts from this blog

Promises in Angular

Mastering Your Angular Workflow: Essential CLI Commands for Efficient Development

Observables in Angular