如何检测 Angular2 中 Date 对象的变化?
How to detect changes with Date objects in Angular2?
使用 setDate 方法修改的日期对象不会在模板中更新。
在模板中:
<p>{{date | date:'mediumDate'}}</p>
在组件中:
nextDay(){
this.date.setDate(this.date.getDate()+1);
}
但是当我调用 nextDay 函数时,模板没有更新为新值。
让变化检测工作的唯一方法是这样做:
nextDay(){
var tomorrow = new Date();
tomorrow.setDate(this.date.getDate()+1);
this.date = tomorrow;
}
是否有更好的方法来完成同样的任务?
我认为更改日期变量的引用是正确的方法。从文档 here 我们有:
The default change detection algorithm looks for differences by comparing bound-property values by reference across change detection runs.
因此,如果日期参考保持不变,则不会发生任何事情。您需要一个新的 Date 引用,这就是 nextDay()
第二个版本起作用的原因。
如果删除格式化管道,您会发现仍然只有 nextDay()
的第二个版本有效。
使用 setDate 方法修改的日期对象不会在模板中更新。
在模板中:
<p>{{date | date:'mediumDate'}}</p>
在组件中:
nextDay(){
this.date.setDate(this.date.getDate()+1);
}
但是当我调用 nextDay 函数时,模板没有更新为新值。
让变化检测工作的唯一方法是这样做:
nextDay(){
var tomorrow = new Date();
tomorrow.setDate(this.date.getDate()+1);
this.date = tomorrow;
}
是否有更好的方法来完成同样的任务?
我认为更改日期变量的引用是正确的方法。从文档 here 我们有:
The default change detection algorithm looks for differences by comparing bound-property values by reference across change detection runs.
因此,如果日期参考保持不变,则不会发生任何事情。您需要一个新的 Date 引用,这就是 nextDay()
第二个版本起作用的原因。
如果删除格式化管道,您会发现仍然只有 nextDay()
的第二个版本有效。