angular2 @input - change detection

21,856

Solution 1

Yeah, you can use OnChanges lifecycle event:

@Input() inputData: InputData;

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

Read more about Angular's lifecycle events here.

Solution 2

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
    }
 }

}

Solution 3

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

Solution 4

You could listen to OnChanges component lifecycle event inside your component

ngOnChanges(model: SimpleChanges){
   console.log(model)
}
Share:
21,856
gka
Author by

gka

Updated on July 09, 2022

Comments

  • gka
    gka almost 2 years

    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;