Date not updating after change of a month
Asked Answered
U

1

9

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");
}
Unilingual answered 24/1, 2018 at 21:21 Comment(0)
A
16

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());
  }
}
Ammonic answered 24/1, 2018 at 22:35 Comment(2)
that was great ty alotUnilingual
This is gold. Even before trying this code, I knew that this would work. ThanksTagmemic

© 2022 - 2024 — McMap. All rights reserved.