Angular Material click next month or previous month not working

2.4k Views Asked by At

Code snippet:

<mat-calendar *ngIf="dataAvailable" #openCalendar [dateClass]="getAttendance()" (selectedChange)="onSelect($event)" (monthSelected)="monthSelected($event)"> </mat-calendar>

Angular Material does not gives any option to call some event while clicking on next and previous month. Is there work around if we need to use Angular Material calendar?

1

There are 1 best solutions below

0
On

For those who still search a solution for this problem, you can access the previous & next arrows with query selectors in ngAfterViewInit, its maybe not the best way but it works for me

ngAfterViewInit(): void {
  const BACK_BUTTON = document.querySelector('.mat-calendar-previous-button');
  const FORWARD_BUTTON = document.querySelector('.mat-calendar-next-button');
  if (BACK_BUTTON) {
    this.renderer.listen(BACK_BUTTON, 'click', () => {
      console.log(this.dateAdapter.today());
      if (this.calendarDate.getMonth() === 0) {
        this.calendarDate.setFullYear(this.calendarDate.getFullYear() - 1);
        this.calendarDate.setMonth(11);
      } else {
        this.calendarDate.setMonth(this.calendarDate.getMonth() - 1);
      }
    });
  }
  if (FORWARD_BUTTON) {
    this.renderer.listen(FORWARD_BUTTON, 'click', () => {
      if (this.calendarDate.getMonth() === 11) {
        this.calendarDate.setFullYear(this.calendarDate.getFullYear() + 1);
        this.calendarDate.setMonth(0);
      } else {
        this.calendarDate.setMonth(this.calendarDate.getMonth() + 1);
      }
    });
  }
}