0

I'm currently working on a project that involves using Angular Material's MatDatePicker (range Selection) component to display a calendar with custom styling for specific dates. I've encountered an issue while trying to apply custom CSS classes to certain calendar cells based on specific conditions.

Here's a snippet of my code:

 <mat-form-field appearance="outline" class="col-3 date-picker" (click)="picker2.open()">
          <mat-label>start date</mat-label>
          <mat-date-range-input class="special-element" [rangePicker]="picker2" [dateFilter]="dateFilter">
            <input matEndDate
              [readonly]="true" (dateChange)="changeDate('endDate')">
            <input matStartDate (dateChange)="changeDate('startDate')"[readonly]="true">

          </mat-date-range-input>

          <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
          <mat-date-range-picker #picker2></mat-date-range-picker>
        </mat-form-field>

Any suggestions please ?

Emna Azizi
  • 21
  • 3

1 Answers1

1

You can add .mat-calendar-body-cell-container css declaration in your global styles.css.

.mat-calendar-body-cell-content {
  color: white;
}


.mat-calendar-body-cell-container {
  background-color: green !important;
}

example of a datepicker with custom color

Edit:

What you can do is the following:

export class YourComponent implements AfterViewInit {
  range =  new FormGroup({
    start: new FormControl(), end: new FormControl()
  });

  @ViewChild('picker2') picker!: MatDatepicker<Date>;

  ngAfterViewInit(): void {
    this.picker.dateClass = (date: Date) => {
      return {
        ['cell-class']: (date.getDate() % 2 === 0)
      }
    }
  }
}

Then on your global styles.css you can define cell-class.

.cell-class {
    background-color: red !important /* you must include important */
}

For this example, it applies color to all even days.

Reference: MatCalendarCellClassFunction

trabeast
  • 26
  • 3
  • i actually want to color specific dates , not the calendar – Emna Azizi Aug 10 '23 at 12:14
  • I have edited my answer. So the function accepts and object where the keys are class names and the value is boolean. So you can create your own logic to color specific dates. – trabeast Aug 10 '23 at 15:34