How to detect changes with Date objects in Angular2?

Date objects that are modified using the setDate method are updated in the template.

In the template:

<p>{{date | date:'mediumDate'}}</p> 

In component:

  nextDay(){ this.date.setDate(this.date.getDate()+1); } 

But when I call the nextDay function, the template is not updated with the new value.

The only way I could work with change detection was as follows:

  nextDay(){ var tomorrow = new Date(); tomorrow.setDate(this.date.getDate()+1); this.date = tomorrow; } 

Is there a better way to accomplish this same task?

+7
javascript date angular angular2-template
source share
1 answer

I think this is the right way to change the date variable reference. From the documents here we have:

The change detection algorithm, by default, looks for differences by comparing the values โ€‹โ€‹of the attached properties by reference through change detection runs.

So, if the date reference remains the same, nothing will happen. You need a new Date link, and why the second version of nextDay() works.

If you remove the format pipe, you will see that only the second version of nextDay() works.

+5
source share

All Articles