Angular Material Datepicker: `dateClass` callback - Accessing Component's Properties and `this` Context

92 Views Asked by At

I'm using Angular with Angular Material and Datepicker. I want to customize the CSS of specific dates in the Datepicker by applying a custom class. I'm utilizing the dateClass parameter with an @Input() decorator to achieve this.

However, I'm facing issues with the implementation:

  1. Accessing Component's Properties: In the dateClassCallback method, I need to access a property called dateToCustom which is an array of dates that should be styled differently. However, since this inside the dateClassCallback refers to the NgxMatMonthView rather than my component, I'm unable to access dateToCustom.

  2. Closure and arrow functions are called properly but they are not adding any class to dates as expected.

I have referred to the official Angular Material documentation, this question and also this one, but I couldn't find a solution to these issues.

Here's a simplified version of my code:

    @Component({
      // Component configuration
    })
    export class MyComponent {
      dateToCustom: Date[] = [
        new Date('2023-05-20'),
        new Date('2023-05-25'),
        // ...
      ];
    
      dateClassCallback = (date: Date): MatCalendarCellCssClasses => {
        // Need access to dateToCustom, but unable to retrieve it here
        return this.dateToCustom.includes(date) ? 'myCustomClass' : '';
      };
    }

I would greatly appreciate any guidance or suggestions on how to overcome these issues and properly access the component properties within the dateClassCallback function. Thank you in advance for your help.

0

There are 0 best solutions below