Richard77
Richard77

Reputation: 21609

How to detect that a bound property's value has changed in angular 4

This is how you detect that a property decorated with @Input has changed:

export class EmployeeComponent implements OnChanges {
  @Input() message: string;
  startDate: Date;

  ngOnChanges(changes: SimpleChanges) {
     for (let propName in changes) {  
        let change = changes[propName];
        if (propName === 'message') {
          //do something...
        }
     }
  }
}

Here's the markup

<app-date-picker [(model)]="startDate"></app-date-picker>

startDate is not decorated by @Input, but I'd like to do something if the value of startDate changes.

Thanks for helping

Upvotes: 0

Views: 420

Answers (2)

CruelEngine
CruelEngine

Reputation: 2841

You can do this :

<app-date-picker [(model)]="startDate" (modelChange)='dateChanged($event)'></app-date-picker>

reason for using (modelChange) is simple , [(model)] uses two way data binding for the variable bound . So i can use [model] and (modelChange) .

The Other way is mentioned by @Sajeetharan . So Choose whichever you want . Let me know if this works.

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222522

You can use the (onChanged) event on the date picker as follows,

<app-date-picker [(model)]="startDate" (onChanged)="onDateChanged()"></app-date-picker>

and in TS,

 onDateChanged() {
     access the changes here 
 }

Upvotes: 2

Related Questions