pb4*_*now 3 typescript date-pipe angular
我只是简单地查看可以更改一个月的位置:
<button class="btn btn-primary" (click)="switchToPrevMonth()"><</button>
{{currentDate|date:'MMMM'}}
<button class="btn btn-primary" (click)="switchToNextMonth()">></button>
Run Code Online (Sandbox Code Playgroud)
然后在我的.ts中:
ngOnInit() {
this.currentDate = new Date();
}
switchToNextMonth() {
this.currentDate.setMonth(this.currentDate.getMonth()+1)
this.cdRef.detectChanges()
}
switchToPrevMonth() {
this.currentDate.setMonth(this.currentDate.getMonth()-1)
this.cdRef.detectChanges()
}
Run Code Online (Sandbox Code Playgroud)
但它不会刷新日期-我通过创建在ts中使用DatePipe的方法getDate()使其工作(请参见下面的代码)并返回一个字符串,但想知道为什么第一种情况不起作用以及是否存在这种情况是使它工作的一种方法...?:s
起作用的代码:
<button class="btn btn-primary" (click)="switchToPrevMonth()"><</button>
{{getDate()}}
<button class="btn btn-primary" (click)="switchToNextMonth()">></button>
Run Code Online (Sandbox Code Playgroud)
.ts:
getDate():string{
return this.dp.transform(this.currentDate,"MMMM");
}
Run Code Online (Sandbox Code Playgroud)
修改Date对象时,Angular不会检测到任何更改。强制更改检测的一种方法是,每次修改日期时都创建一个新的Date对象。您可以在此stackblitz中看到它无需ChangeDetectorRef.detectChanges手动调用即可工作(除非,如果您的组件使用ChangeDetectionStrategy.OnPush)。
export class MyComponent implements OnInit {
public currentDate: Date;
ngOnInit() {
this.currentDate = new Date();
}
switchToNextMonth() {
this.incrementMonth(1);
}
switchToPrevMonth() {
this.incrementMonth(-1);
}
private incrementMonth(delta: number): void {
this.currentDate = new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth() + delta,
this.currentDate.getDate());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1046 次 |
| 最近记录: |