I\'m trying to detect when the value of an input changed in a directive. I have the following directive:
There is a better way to detect when an Input
property changes, it's considered a best practice and it's also used in the *ngIf implementation.
You just need to postpone the keyword set
after Input()
, in this way you combine the @Input()
decorator with a setter
, and it gets called all the times the value changes.
_rows: number;
@Input() set rows(value: number) {
if (this.value < 0) {
console.error('The number of rows must be positive');
this._rows = 2;
return;
}
this._rows = value;
}
If you want to compare the new value with the previous value, you must store the variable in a class property, and retrieve it the second time the method got called:
private previousValue: any = T;
@Input() set myInputName(value: T) {
console.log(`Previous value was: ${this.previousValue}`);
console.log(`New value is: ${value}`);
this.previousValue = value;
}