18

Is there a way to listen for @Input change?

In following example, I would like to be informed whenever 'inputData' value is changed.

@Input() inputData: InputData;
gka
  • 499
  • 2
  • 6
  • 14

4 Answers4

22

Yeah, you can use OnChanges lifecycle event:

@Input() inputData: InputData;

ngOnChanges() {
    console.log(this.inputData);
}

Read more about Angular's lifecycle events here.

Stefan Svrkota
  • 48,787
  • 9
  • 98
  • 87
21
import { Component, Input, OnChanges, SimpleChange } from '@angular/core';


export class Demo implements OnChanges {

 @Input() inputData: InputData;
 ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {

    if (changes['inputData'] && this.inputData) {

        //your logic work when input change
    }
 }

}
yala ramesh
  • 3,362
  • 1
  • 22
  • 35
6

you can use something like :

Input('value')
set value(val: string) {
  this._value = val;
  console.log('new value:', value); // <-- do your logic here!
}

more info available at this link

you can also take a look at this article

Community
  • 1
  • 1
Amir Ghezelbash
  • 2,195
  • 15
  • 24
3

You could listen to OnChanges component lifecycle event inside your component

ngOnChanges(model: SimpleChanges){
   console.log(model)
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299