Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 830
gka Avatar asked Jan 18 '17 18:01

gka


People also ask

What is change detection How does change detection mechanism work?

Change detection works by detecting common browser events like mouse clicks, HTTP requests, and other types of events, and deciding if the view of each component needs to be updated or not.

How do you identify changes in Angular components?

To run the change detector manually: Inject ChangeDetectorRef service in the component. Use markForCheck in the subscription method to instruct Angular to check the component the next time change detectors run. On the ngOnDestroy() life cycle hook, unsubscribe from the observable.

How do I detect a text input change event with Angular?

When we enter tags one character at a time, Angular performs change detection after every character is entered. So, if we type in “foo”, the Angular binding records for the <input> element value attribute will follow this sequence: "" , "f" , "fo" , "foo" .


Video Answer


4 Answers

Yeah, you can use OnChanges lifecycle event:

@Input() inputData: InputData;

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

Read more about Angular's lifecycle events here.

like image 131
Stefan Svrkota Avatar answered Oct 19 '22 17:10

Stefan Svrkota


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

}
like image 38
yala ramesh Avatar answered Oct 19 '22 19:10

yala ramesh


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

like image 44
Amir Ghezelbash Avatar answered Oct 19 '22 19:10

Amir Ghezelbash


You could listen to OnChanges component lifecycle event inside your component

ngOnChanges(model: SimpleChanges){
   console.log(model)
}
like image 3
Pankaj Parkar Avatar answered Oct 19 '22 19:10

Pankaj Parkar