Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date not updating after change of a month

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");
}
like image 873
pb4now Avatar asked Jan 24 '18 21:01

pb4now


1 Answers

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());
  }
}
like image 194
ConnorsFan Avatar answered Sep 21 '22 03:09

ConnorsFan