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.
4 Answers
You can simply use MatCalendar.updateTodaysDate()
to re-render it.
@ViewChild(MatCalendar) calendar: MatCalendar<Date>;
someEvent(){
this.calendar.updateTodaysDate();
}

- 620
- 1
- 10
- 17
-
1This works when using Date class calendar - but not with moment! – Ian Grainger Mar 30 '21 at 05:59
-
This worked for me, and my calendar returns Moment when selecting a date – Florin Filip Sep 16 '21 at 13:47
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';
}

- 69
- 3
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

- 29
- 2
-
Sorry, this did nothing I could see. The rendering optimiser will treat that as no change. – Ian Grainger Mar 30 '21 at 05:53
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...

- 1,218
- 12
- 16