Date objects that are modified using setDate method arent getting updated in template.
In template:
<p>{{date | date:'mediumDate'}}</p>
In component:
nextDay(){
this.date.setDate(this.date.getDate()+1);
}
But when I call nextDay function, the template isnt updated with the new value.
The only way I could get the change detection working was doing this:
nextDay(){
var tomorrow = new Date();
tomorrow.setDate(this.date.getDate()+1);
this.date = tomorrow;
}
Are there a better way to accomplish this same task?
To run the change detector manually: Inject ChangeDetectorRef service in the component. Use markForCheck in the subscription method to instruct Angular to check the component the next time change detectors run. On the ngOnDestroy() life cycle hook, unsubscribe from the observable.
If you need to detect changes in objects inside an array, you will need to iterate through all elements, and apply KeyValueDiffers for each element. (You can do this in parallel with previous check).
Angular 2's change detection system is built on top of zone. js hooks. Once an asynchronous action completes, Angular 2 starts its change detection routine. This means traversing all of the nodes in the "component tree" always starting with the root node.
I think that is the right way, to change the reference of the date variable. From the docs here we have:
The default change detection algorithm looks for differences by comparing bound-property values by reference across change detection runs.
So if the date reference remains the same, nothing will happen. You need a new Date reference and that's why the second version of nextDay()
works.
If you remove the formatting pipe you will see that still only the second version of nextDay()
works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With