2016-01-24 45 views
1

我對Angular 2.0中的雙向綁定有個疑問。 在我看來,我顯示了選定的日期(月和年)+本月的天數。 有按鈕可以進入下一個或上個月。 但是,當我點擊它們顯示日期不更新,但它已成功更新模型中。並在本月的日子正確更新(與ngFor)。 有沒有人知道在視圖中更新日期的正確方法?Angular 2.0中的雙向綁定日期

查看:

<span> 
    {{date | date:'MMMM yyyy'}} 
</span> 

<button (click)="goToPreviousMonth()">Previous month</button> 
<button (click)="goToNextMonth()">Next month</button> 

<div *ngFor="#week of weeks"> 
    <!-- Show days --> 
</div> 

組件:

import {Component} from 'angular2/core'; 
import {CORE_DIRECTIVES, NgModel} from 'angular2/common'; 

@Component({ 
    selector: 'monthview', 
    templateUrl: './monthview.html', 
    directives: [CORE_DIRECTIVES] 
}) 
export class MonthView { 
    weeks:any = []; 
    date:Date; 

    public goToMonthFromCurrent(addMonth:number) : void { 
     // Update date 
     this.date.setMonth(this.date.getMonth() + addMonth); 

     // Some other code to calculate days of month... 

     // This will update the date in view 
     this.date = new Date(this.date.getTime()); 
    } 

    public goToNextMonth() : void { 
     this.goToMonthFromCurrent(1); 
    } 

    public goToPreviousMonth() : void { 
     this.goToMonthFromCurrent(-1); 
    } 
} 

回答

0

如果你改變一個對象Angulars變化檢測不承認變化的特性。 Angular只會比較對象實例的身份。

創建一個新的Date實例,而不是更改現有的實例。

+0

謝謝。 'this.date = new Date(this.date.getTime());'確實是解決方案(有問題的更新解決方案)。解決方案將如何通知角度更改? – user2276975