首页 > 解决方案 > Angular 中的日期类型绑定时会发生什么

问题描述

为什么是 mydate(一种日期)。setMonth(mydate.getMonth()+1)不会在视图中导致角度刷新 mydate?

当我使用时, mydate = new Date(mydate.setMonth(mydate.getMonth()+1)); view 会得到正确的值吗?

test.component.html

<label>{{currentDate | date:'MMM'}}</label>
<button (click)="nextMonth()">Next</button>

代码 1

测试组件.ts

currentDate: Date = new Date(); // get now
// others ...
nextMonth() {
  this.currentDate.setMonth(this.currentDate.getMonth() + 1);
}

预期结果

当我单击“下一步”按钮时,标签将显示下个月的月份。

实际结果

单击“下一步”按钮时没有任何变化。当我在 nextMonth 方法结束时 console.log(this.currentDate) 显示下个月的值。但观点没有变化。

代码 2

测试组件.ts

currentDate: Date = new Date(); // get now
// others ...
nextMonth() {
  this.currentDate = new Date(this.currentDate.setMonth(this.currentDate.getMonth() + 1));
}

预期结果和实际结果

单击“下一步”按钮,标签值发生变化。

标签: angular

解决方案


你可以这样试试:

  locale = "en-us";
  currentMonth = new Date().toLocaleString(this.locale, {
      month: "long"
   });

 nextMonth() {
  this.currentDate.setMonth(this.currentDate.getMonth() + 1);
  this.currentMonth =  this.currentDate.toLocaleString(this.locale, {
  month: "long"
  });
}

然后在你的 test.component.html 中使用

<label>{{currentMonth}}</label>
<button (click)="nextMonth()">Next</button>

推荐阅读