Reputation: 331
my issue is related to Angular material but JavaScript logic is causing me issue. I have an object
[ {
"type": "holiday",
"date": "2019-07-04",
"releaseWindow": {
"start": null,
"end": null
},
"description": "HMHS Holiday",
"linkable": false
}]
if type of date is holiday then apply red color to calendar. I used switch statement for that
// dateClass is used to apply color to calendar. If dates of calendar is matching with dates from sample data then color will be applicable
dateClass() {
return (date: Date): MatCalendarCellCssClasses => {
for (const items of this.datesArray) {
switch (items.type) {
case 'holiday':
if (moment(items.date).year() === date.getFullYear() && moment(items.date).month() === date.getMonth() && moment(items.date).date() === date.getDate()) {
this.holiday = true; /// apply red color
} else {
this.holiday = false; /// no color
}
break;
default:
break;
}
}
return [this.holiday ? 'holiday' : ''];
}; // if this.holiday is true then apply red color to background
}
Below is my stackblitz link. https://stackblitz.com/edit/ang-c-p-5htnub?file=app%2Fapp.component.ts
if you take single single object from the sample data, then you will see colors are applicable appropriately. But when you take bunch of data then its not applicable.
For example for date "2019-07-04", in the calendar background should be red but its not. If you delete everything from the sample data and take only first object (date:"2019-07-04")then css class is applicable.
Upvotes: 2
Views: 109
Reputation: 17032
I believe you have way over-complicated the method you have. Here is a simplified example: https://stackblitz.com/edit/ang-c-p-5fbu1h?file=app%2Fapp.component.ts
dateClass() {
// This actually gets called for **EACH** date that's being rendered.
// Keep this in mind.
return (calendarDate: Date): MatCalendarCellCssClasses => {
const key = moment(calendarDate).format('YYYY-MM-DD');
let date = null;
if(this.datesArray) {
const result = this.datesArray.filter((d: any) => d.date === key);
if(result.length > 0) {
date = result[0];
}
}
let cssClasses = '';
if(date) {
cssClasses = date.type;
if(date.linkable === true) {
cssClasses += ' set_your_linkable_class';
}
}
return cssClasses;
};
}
If I were you, I'd also restructure the data or refactor the backend to return the data in a map
format so that you can directly do this.datesArray['2019-07-12']
and get the object directly instead of having to loop through all dates to filter it out.
Upvotes: 2