Reputation: 4062
The view is rendered properly initially so I know the service is working when the page loads, but what I trigger decrementDate()
or incrementDate()
the new date is alert()
ed, but the view is not updated. What am I not understanding?
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);
}
}
template:
<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>
Upvotes: 1
Views: 116
Reputation: 2915
What you're running into is Angular2's change detection. It's assuming data immutability, so when you're calling the .setDate() function, it doesn't actually know that anything has changed, because it's not looking for it. Instead, you should set the property to a new Date.
Example:
let newDate = new Date(this.workingData.selectedDate.getTime());
newDate.setDate(newDate.getDate() - 1);
this.workingData.selectedDate = newDate;
Upvotes: 1