Search code examples
javascriptangulartypescriptangular-material

How to programmatically change the month in Material Calendar <mat-calendar>


I'm using the Material Calendar Component with custom navigation that I've built which shows the next 5 days after you select a date in the calendar.

When you select a date in the custom element it updates the Calendar with the newly selected date, but if the incoming date is in the next month, I would like the Calendar, to switch to that month automatically.

HTML:

<mat-calendar [selected]="selectedDate" (selectedChange)="onDateSelected($event)"
  [minDate]="minDate" [dateClass]="dateClass"></mat-calendar>

TS:

@Input() set incomingDate(d: Date) {
    this.selectedDate = d; // sets the incoming date on mat-calendar
    this.dateClass(d); // highlights the next 5 days in the mat-calendar
    this.calendar.updateTodaysDate(); // re-renders calendar to see changes
}

Is there any method that I can bind to the element to solve this problem? Thank you!


Solution

  • You can use _goToDateInView for that. It won't change the date object, it will just go to the month you pass as a parameter, therefore you can keep your date selection logic intact.

    /** Handles year/month selection in the multi-year/year views. */
    _goToDateInView(date: D, view: 'month' | 'year' | 'multi-year'): void;
    

    And here is how you could use it:

    Template

    <mat-calendar #calendar></mat-calendar>
    

    Component

    @ViewChild('calendar', {static: false}) calendar: MatCalendar<Date>;
    
    public goToDate() {
       this.calendar._goToDateInView(someDateObjectInAnotherMonth, 'month')
    }
    

    Stackblitz