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?

Kevin Yan
  • 1,236
  • 11
  • 19
Renato Souza de Oliveira
  • 4,236
  • 4
  • 20
  • 31

2 Answers2

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; }
Mathias
  • 1,819
  • 4
  • 22
  • 34
3

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

https://stackoverflow.com/a/61720541/13514355

  • This is in fact the correct answer. Now sure why it was voted down! Direct link to Angular document: https://angular.io/api/core/OnChanges – Sarang Aug 07 '20 at 10:54
  • 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: https://medium.com/@isaacplmann/ngonchanges-only-runs-when-the-input-change-comes-from-a-template-binding-like-component-8797b759ba0b From this point of view, I would say the get / set solution in blog above or by @Mathias is better, but I don't like the use of private variable. – Sarang Aug 07 '20 at 11:16