angular - How can I get my Angular2 DatePipe-formatted Date to update? -
sample of issue: http://plnkr.co/edit/7feroyyqdnjxpv9q9vpy?p=preview
import {component, ngmodule} '@angular/core' import {browsermodule} '@angular/platform-browser' @component({ selector: 'my-app', template: ` <div> <h2>{{mydate}}</h2> <!-- updates expected --> <h2>{{mydate | date: 'longdate'}}</h2> <!-- not --> <a (click)="prevmonth()" href="javascript:;">previous month</a> <a (click)="nextmonth()" href="javascript:;">next month</a> </div> `, }) export class app { mydate: date; constructor() { this.mydate = new date(); } nextmonth() { this.mydate.setmonth(this.mydate.getmonth() + 1); } prevmonth() { this.mydate.setmonth(this.mydate.getmonth() - 1); } } @ngmodule({ imports: [ browsermodule ], declarations: [ app ], bootstrap: [ app ] }) export class appmodule {} when pass variable without using pipes, updates expected. datepipe-formatted copy of same variable not update. pipe update observables? or can use standard date type , expect update in realtime?
i not see in datepipe api suggests expected behavior, i've narrowed down point datepipe affecting bahavior in way. https://angular.io/docs/ts/latest/api/common/index/datepipe-pipe.html
it doesn't work because angular2's datepipe stateful (the pure property set true in decorating function). stateful pipes applied once on given object. can change pipe definition (not in a2 source of course) or make force data change.
so first way solve create , use new stateless pipe:
@pipe({name: 'mydate', pure: false}) export class mydatepipe implements pipetransform { transform(value: any, pattern: string = 'mediumdate'): string { return (new datepipe()).transform(value, pattern); } } i've prepared plnkr example. it's simple , reusable, recommend solution small data.
although, can solved using changedetector , markforcheck() method after every date update - 1 more efficient. or dmitry said, create new date object everytime want change data.
Comments
Post a Comment