Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh mat-calendar after changing the background of highlighted dates

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

like image 607
adarsh Avatar asked May 10 '19 19:05

adarsh


3 Answers

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

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

someEvent(){
    this.calendar.updateTodaysDate();
}
like image 154
Jie Wang Avatar answered Oct 17 '22 08:10

Jie Wang


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';
}
like image 29
Esteban Arredondo Avatar answered Oct 17 '22 09:10

Esteban Arredondo


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

like image 1
María Teresa Avatar answered Oct 17 '22 09:10

María Teresa