I just making a simple view where I can Change a month :
<button class="btn btn-primary" (click)="switchToPrevMonth()"><</button>
{{currentDate|date:'MMMM'}}
<button class="btn btn-primary" (click)="switchToNextMonth()">></button>
and then in my .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()
}
but it doesn't refresh the date - I made it work by creating a methode getDate() that uses DatePipe in ts(look code below) and returns a string but would like to know why the first case didn't work and if there is a way to make it work...?:s
code that works:
<button class="btn btn-primary" (click)="switchToPrevMonth()"><</button>
{{getDate()}}
<button class="btn btn-primary" (click)="switchToNextMonth()">></button>
.ts:
getDate():string{
return this.dp.transform(this.currentDate,"MMMM");
}
Angular does not detect any change when the Date object is modified. One way to force change detection is to create a new Date object every time you modify the date. You can see in this stackblitz that it works without invoking ChangeDetectorRef.detectChanges
manually (except, maybe, if your component uses 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());
}
}
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