ngOnChanges not firing if an @Input is receiving an object
Like this:
@Input() public param: any;
ngOnChanges(changes: SimpleChanges): void {
// Do your check here
console.log(changes.param.previousValue);
}
Using changes gets you access to previousValue and currentValue.
Angular change detection is triggered when the @Input property value changes.
So to trigger change detection in case of an object you could pass a copy of the object using spread operator as the input.
for eg. someVar = {key: value}
this is @Input()
variable, so pass like
<app-sample [someVar]="{...someVar}" ></app-sample>
{...VARIABLE}
<- here is the magic
if spread operator won't work use any object deep copying methods like
JSON.parse(JSON.stringify(obj))
The OnChanges lifecycle hook is triggered when the @Input
property value changes. In the case of an object, that value is the object reference. If the object reference does not change, OnChanges
is not triggered.
A possible technique to force change detection is to set a new object reference after modifying the property values:
this.whatever.value1 = 2;
this.whatever.value2 = 3;
this.whatever = Object.assign({}, this.whatever);
The ngOnChanges
event handler can then be used to monitor the changes:
ngOnChanges(changes: SimpleChanges) {
for (let propName in changes) {
let chng = changes[propName];
let cur = JSON.stringify(chng.currentValue);
console.log(propName, cur);
}
}
As an alternative, if @Input
decorates a getter/setter property, the changes can be monitored in the setter:
private _param: Object;
@Input() get param(): Object {
return this._param;
}
set param(value: Object) {
console.log("setter", value);
this._param = value;
}
See this stackblitz for a demo.