视图最初正确呈现,因此我知道服务在页面加载时正在运行,但我触发decrementDate()
或incrementDate()
新日期为alert()
,但视图没有更新。 我不理解的是什么?
export class CalNavComponent implements OnInit {
workingData: WorkingData;
constructor(private _workingDataService: WorkingDataService) { }
getWorkingData(): void {
this._workingDataService.getWorkingData().then(workingData => this.workingData = workingData);
}
ngOnInit(): void {
this.getWorkingData();
}
decrementDate(): void {
this.workingData.selectedDate.setDate(this.workingData.selectedDate.getDate() - 1);
alert(this.workingData.selectedDate);
}
incrementDate(): void {
this.workingData.selectedDate.setDate(this.workingData.selectedDate.getDate() + 1);
alert(this.workingData.selectedDate);
}
}
模板:
<div class="cal-nav">
<div class="cal-nav-item">
<md-icon class="cal-nav-icon" (click)="decrementDate()">chevron_left</md-icon>
</div>
<div class="cal-nav-item cal-nav-date">
{{workingData?.selectedDate | date: "d MMM y"}}
</div>
<div class="cal-nav-item">
<md-icon class="cal-nav-icon" (click)="incrementDate()">chevron_right</md-icon>
</div>
</div>
答案 0 :(得分:1)
您正在遇到的是Angular2的变更检测。它假设数据不变,所以当你调用.setDate()函数时,它实际上并不知道任何事情已经改变,因为它没有找到它。相反,您应该将属性设置为新的日期。
示例:
let newDate = new Date(this.workingData.selectedDate.getTime());
newDate.setDate(newDate.getDate() - 1);
this.workingData.selectedDate = newDate;