angular - 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));
}
预期结果和实际结果
单击“下一步”按钮,标签值发生变化。
解决方案
你可以这样试试:
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>
推荐阅读
- javascript - 无法在 Angular 项目中使用 bpmn.js、bpmn-viewer.js、differ.js 和 change-handler.js 文件
- java - 如何使用 java 在 kubernetes pod 中创建 mysql 转储文件
- openssl - 如何使openssl ocsp响应者忙
- python - 当 MQTT 客户端尝试在没有互联网的情况下连接时如何处理?
- angular - AngularFire firebase 中有没有一种方法可以在一个查询中获取多路径数据
- c# - 处理清单失败:Xamarin.Forms
- c# - FFMPEG - 入门
- javascript - 如何在 append 和 prepend 函数之间动态选择?
- laravel - 如何修复 Laravel,达到“256”的最大函数嵌套级别,中止
- azure - 授权 Slack 机器人