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:
- React to
Input Changes: Fetch
data, recalculate values, or run logic when an input changes.
- Reset
Internal State: Clear or
update internal variables based on new inputs.
- Track
Previous vs Current Values:
Useful for logs or conditional operations.
- Conditional
API Calls: Trigger
HTTP or DOM updates when inputs meet criteria.
- 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:
- Use
ngDoCheck: Called
during every change detection cycle.
- 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
Post a Comment