gka
gka

Reputation: 509

angular2 @input - change detection

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;

Upvotes: 18

Views: 23170

Answers (4)

yala ramesh
yala ramesh

Reputation: 3362

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

}

Upvotes: 21

Amir Ghezelbash
Amir Ghezelbash

Reputation: 2415

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

Upvotes: 6

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

You could listen to OnChanges component lifecycle event inside your component

ngOnChanges(model: SimpleChanges){
   console.log(model)
}

Upvotes: 3

Stefan Svrkota
Stefan Svrkota

Reputation: 50643

Yeah, you can use OnChanges lifecycle event:

@Input() inputData: InputData;

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

Read more about Angular's lifecycle events here.

Upvotes: 22

Related Questions