如何检测Angular2中Date对象的变化? [英] How to detect changes with Date objects in Angular2?

查看:28
本文介绍了如何检测Angular2中Date对象的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 setDate 方法修改的日期对象不会在模板中更新.

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

在模板中:

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

在组件中:

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

但是当我调用 nextDay 函数时,模板不会更新为新值.

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?

推荐答案

我认为这是正确的方法,更改日期变量的引用.从文档这里我们有:

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.

因此,如果日期引用保持不变,则不会发生任何事情.您需要一个新的 Date 引用,这就是 nextDay() 的第二个版本起作用的原因.

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.

如果您移除格式化管道,您将看到仍然只有 nextDay() 的第二个版本有效.

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

这篇关于如何检测Angular2中Date对象的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆