How to detect changes with Date objects in Angular

2020-04-05 07:42发布

问题:

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

In template:

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

In component:

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

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

The only way I could get the change detection working was doing this:

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

Are there a better way to accomplish this same task?

回答1:

I think that is the right way, to change the reference of the date variable. From the docs here we have:

The default change detection algorithm looks for differences by comparing bound-property values by reference across change detection runs.

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

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