Home > Net >  Highlight dates in a datepicker based on list of dates in Angular
Highlight dates in a datepicker based on list of dates in Angular

Time:11-18

I have an array with a list of dates with flag for availability.

For Ex: -

[
   {
     ...
     date : 2021-11-18
     isAvailable : true,
     ...
   },
   {
     ...
     date : 2021-11-19
     isAvailable : false,
     ...
   }
]

I have to use this data to add an icon(green/red) below dates in datepicker when isAvailable is true or false.

I have to use angular material datepicker.

I don't know where to begin.

CodePudding user response:

TS

dateArr = [
    {
        date: "2021-11-18",
        isAvailable: true
    },
    {
        date: "2021-11-19",
        isAvailable: false
    }
]

dateClass: MatCalendarCellClassFunction<Date> = (cellDate, view) => {
    const index = this.dateArr.findIndex(x => new Date(x.date).toLocaleDateString() === cellDate.toLocaleDateString());
    if (index > -1) {
        if (this.dateArr[index].isAvailable) {
            return "date-red";
        } else if (!this.dateArr[index].isAvailable) {
            return "date-green";
        }
    }

    return '';
};

HTML

<input matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker [dateClass]="dateClass" #picker></mat-datepicker>

CSS

.date-red {
    border-bottom: 10px solid #FF0000;
}

.date-green {
    border-bottom: 10px solid #00FF00;
}
  • Related