Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect changes with Date objects in Angular2?

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?

like image 990
nsbm Avatar asked Jan 15 '16 20:01

nsbm


People also ask

How do you identify changes in Angular components?

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.

How do you find change in an array?

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).

Which is used to detect changes in angular 2?

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.


1 Answers

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.

like image 124
Angular University Avatar answered Sep 22 '22 15:09

Angular University