Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting certain dates in mat-calendar

I am using mat-calendar. I am trying to highlight certain dates but I couldn't do it. There is no proper documentation for this.

HTML

<mat-card>
  <mat-calendar name="appointment_date" [selected]="selectedDate (selectedChange)="onSelect($event)"></mat-calendar>
</mat-card>

TS

onSelect(event){
  this.selectedDate= event;
}

What I need:

Image

like image 941
Felix Christo Avatar asked Jan 30 '19 10:01

Felix Christo


2 Answers

Complementing Fabian's answer, if you have problem seeing the highlighted color and you are using lazy loading components, remember to add the ::ng-deep in front of the class. Like this:

::ng-deep.special-date {
   background-color: red;
}

Cheers!

like image 84
Alejandro Barone Avatar answered Oct 30 '22 11:10

Alejandro Barone


You can use the the input binding dateClass as describe in the Angular Material documentation here. Note: This requires an Angular Material version of at least 7.1.0

Change your template to this:

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

And in your component add the dateClass function which will generate a function that will return a type of MatCalendarCellCssClasses, which can be as simple as a string representing the CSS class to apply (or an array of class names):

dateClass() {
  return (date: Date): MatCalendarCellCssClasses => {
    if (date.getDate() === 1) {
      return 'special-date';
    } else {
      return;
    }
  };
}

And finally in your styles.css add the classes you want applied:

.special-date {
  background-color: red;
}

Here is a stackblitz that colors the first of each month in red.

like image 20
Fabian Küng Avatar answered Oct 30 '22 10:10

Fabian Küng