6

I have a mat-calendar control which is open always. On initial load, I am highlighting an array of dates which was able to do following this: Highlighting certain dates in mat-calendar. Now I have to highlight today's day (or selected date) on a button click. The highlighting works only when I change to different month, and then come back to the current month's view. Is there a way to refresh the mat-calendar dynamically? Please advise.

https://am-all-imports-zwnjbd.stackblitz.io

adarsh
  • 173
  • 1
  • 2
  • 11

4 Answers4

18

You can simply use MatCalendar.updateTodaysDate() to re-render it.

@ViewChild(MatCalendar) calendar: MatCalendar<Date>;

someEvent(){
    this.calendar.updateTodaysDate();
}
Jie Wang
  • 620
  • 1
  • 10
  • 17
3

I'm using material 7.2 and for me to move the focus it worked updating the property activeDate:

<mat-calendar
    #myCalendar
    [startAt]="startDate"
    [selected]="selectedDate">
</mat-calendar>

<div>
    <button mat-button (click)="addThreeDays()">
        Add 3 days
    </button>
</div>

Then in the component logic

@ViewChild('myCalendar') myCalendar;
startDate = '2019-08-26';
selectedDate = '2019-08-26';

addThreeDays() {
   this.myCalendar.activeDate = '2019-08-29';
}
1

i haven't found a native method.

here's my workoaround:

put the mat-calendar component inside a div with the condition that the array of highlight dates is not undefined

<mat-card *ngIf="datesToHighlight">
  <mat-calendar [dateClass]="dateClass()" [selected]="selectedDate" (selectedChange)="onSelect($event)"></mat-calendar>
</mat-card>

when you want to refresh mat-calendar, set the array to null and then fill it with the updated data

 this.datesToHighlight = null;
 this.datesToHighlight = getMyNewArray();

That way the component will load again with the new array

0

Other answers with "activeDate" are correct, i just want to point out the reason it does work.

Long story short, @Input("startAt") is not checked for changes in ngOnChanges hook in MatCalendar, you can see it here: Problematic line in MatCalendar repository

And here => activeDate setter, you will see that it actualy triggers a state changes detection.

The weird thing is that activeDate initial value comes from startAt Input when it is set, therefore i believe updating startAt Input should do it too, but it doesn't...

millenion
  • 1,218
  • 12
  • 16