【问题标题】:One way data binding not working when using date pipe使用日期管道时数据绑定不起作用的一种方式
【发布时间】:2017-06-23 23:00:16
【问题描述】:
我正在使用日期对象来跟踪应用程序中的当前日期。
在我看来,我有一个这样的单向绑定:
<h3>{{ currentDate | date }}</h3>
在组件中,我有更改此日期的功能,如下所示:
previousMonth(){
this.currentDate.setMonth(this.currentDate.getMonth() - 1);
}
nextMonth(){
this.currentDate.setMonth(this.currentDate.getMonth() + 1);
}
但是当这些函数被触发时,currentDate 值不会在视图上更新。
我确保日期对象正在更新,只是不在视图上。
每当我删除日期管道时,它都会起作用。
有人知道如何解决这个问题吗?
谢谢!
【问题讨论】:
标签:
date
angular
data-binding
ionic2
【解决方案1】:
视图中的值不会更新,因为默认情况下,角度管道被称为 pure(或无状态)。这意味着如果输入对象发生更改,则不会重新评估输入,但只有在它被替换时才会重新评估。
来自documentation(参见纯和不纯管道部分):
Angular 仅在检测到对
输入值。纯粹的改变要么是对原始输入的改变
值(字符串、数字、布尔值、符号)或更改的对象引用
(日期、数组、函数、对象)。
试试下面的代码:
previousMonth(){
this.currentDate.setMonth(this.currentDate.getMonth() - 1);
this.currentDate = new Date(this.currentDate);
}
nextMonth(){
this.currentDate.setMonth(this.currentDate.getMonth() + 1);
this.currentDate = new Date(this.currentDate);
}