How to Run a Function On Input Change in Angular
We’ll often have @Input()
/@Output()
directives to share data between parent and child components in Angular.
Suppose we have the following input variable flag
.
@Input() flag: boolean = false;
What if we want to run some function whenever the input variable changes?
We can bind a getter and setter to the input property.
_flag: boolean = false;
get flag(): boolean {
return this._flag;
}
@Input() set flag(newFlag: boolean) {
this._flag = newFlag;
this.doSomething();
}
Now, when flag
updates, we’ll run doSomething()
each time.
However, note that mutations to properties that are passed by reference will not trigger the setter of this @Input()
directive. This includes mutating an object and appending to an array.
For instance, pushing a new element to an array or mutating an object will not update that variable in the child component.
Be sure to check out this article to learn how to trigger the setter with properties passed by reference.