Detect change in a variable?
Asked Answered
A

2

14

Is it possible to detect change in a variable?

I have the following:

@Input('name') name: string;

I would like to call a function whenever change is happened in this variable 'name'.

Is it possible?

Arleyne answered 17/10, 2016 at 2:35 Comment(0)
A
8

You can do it the following:

private _name = '';

@Input('name')
set name(name: string) {
   this._name = name;
   doSomeStuff();
}

get name(): string { return this._name; }
Am answered 5/5, 2018 at 7:50 Comment(0)
M
3

I am solve this question using default Angular feature named OnChanges, very similar to OnInit.

https://mcmap.net/q/901328/-variable-change-detection-angular

Monasticism answered 11/5, 2020 at 0:36 Comment(2)
This is in fact the correct answer. Now sure why it was voted down! Direct link to Angular document: angular.io/api/core/OnChangesMollusc
Further to my comment above, I implemented this mechanism and realized that OnChanges is not triggered if change is made outside of the views. A good explanation is here: medium.com/@isaacplmann/… From this point of view, I would say the get / set solution in blog above or by @Am is better, but I don't like the use of private variable.Mollusc

© 2022 - 2024 — McMap. All rights reserved.