user7122183
user7122183

Reputation:

Angular 2 setters vs ngOnChanges

When you want to run some code after the component/directive inputs changes you can use setters or ngOnChanges hook, but what are the benefits of using one on the other? Or they are the same thing exactly?

  @Input()
  set someInput( val ) {
    this.runSomething();
  }

  ngOnChanges(changes) {
     this.runSomething();
  }

Upvotes: 53

Views: 12193

Answers (2)

Temo Kiknadze
Temo Kiknadze

Reputation: 367

There is one important thing in case of setter: Props injected with setter should consider the matter of order

<child [item1]="item1" [item2]="item2"></child>
<child [item2]="item2" [item1]="item1"></child>
// not same if you use setter

So if item2 is setters, item1 some data and you use item1 in item2 it works fine because setter calls the moment value sets, once you change the input order in app template reversed, the app will crash hard because the time item2 is set, item1 is undefined..

Upvotes: 8

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657771

One advantage of ngOnChanges() is that you get all changes at once if your component has several @Input()s.
If your code only depends on a single @Input() a setter is probably the better approach.

Upvotes: 55

Related Questions