The mat-calendar fails to include the specified class when using dateClass functionality

Here are the components of my Calendar:

  <div class="calendarWrapper mat-elevation-z1">
    <mat-calendar [dateClass]="dateClass"></mat-calendar>
  </div>

This is the scss for the custom class to be added:

button.orange {
  background: orange;
  border-radius: 100%;
}

And this is the TypeScript File for the component:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { MatCalendarCellClassFunction } from '@angular/material/datepicker';
import { DateTime } from 'luxon';
import { ColorService } from 'src/app/_services/color.service';
import { AppointmentsDTO } from 'src/app/api/models';
import { WebsiteAppointmentsService } from 'src/app/api/services';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'bookings-element',
  templateUrl: './bookings-element.component.html',
  styleUrls: ['./bookings-element.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class BookingsElementComponent implements OnInit {
  selectedDate: string = '';

  appointments: AppointmentsDTO[] = [];

  constructor(
    public colorService: ColorService,
    private appointmentsService: WebsiteAppointmentsService
  ) {}

  ngOnInit(): void {}

  async getBookings() {
    return new Promise<void>((resolve) => {
      this.appointmentsService
        .getApiWebsiteAppointmentsGetAppointments({
          date: this.selectedDate,
          tenantid: environment.tenantId,
        })
        .subscribe((data: any) => {
          if (data) {
            this.appointments = data;
            resolve();
            console.log(this.appointments);
          }
        });
    });
  }

  dateClass: MatCalendarCellClassFunction<Date> = (cellDate, view) => {
    // Only highligh dates inside the month view.
    if (view === 'month') {
      const date = cellDate.getDate();

      // Highlight the 1st and 20th day of each month.
      return date === 1 || date === 20 ? 'orange' : '';
    }

    return '';
  };
}

There seems to be an issue with adding the custom 'orange' class using the modified dateClass function. Everything else is functioning as expected except for the addition of the class to the buttons. One possible reason could be due to the asynchronous nature of the function, which waits for the API response.

The encapsulation method used in the TS-File appears to be correct, ruling out that as the source of the problem. The expected behavior is for the 'orange' class to be applied to the buttons when the isBooked condition in the dateClass function returns true.

Answer №1

As mentioned earlier, the dateClass should be synchronous as it is not internally awaited in DatePicker. You can refer to the code here.

In your scenario, the functionality of the dateClass relies on data set within the getBookings method, which in turn seems to depend on the currently selected date. You can reorganize the logic accordingly.

Execute the getBookings method when the input value changes, and keep UI locked until a response is received. Then incorporate the existing logic you have.

You can find a demo on stackblitz here.

UPDATE: It appears that your query involves mat-calendar rather than mat-date-picker. Nevertheless, the same principle should apply.

UPDATE2: I have created another stackblitz example for mat-calendar.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Card collapse upon being clicked

I am encountering an issue with a collapsed card in Angular. Here is the code for my component: @Component({ selector: 'app-numbered-card', templateUrl: './numbered-card.component.html', styleUrls: ['./numbered-card.component ...

Discover the best practices for handling state in functional components and customizing styles with FlatList in React Native using TypeScript

Does anyone have a solution to these two issues? 1. When the list is pressed, I want to change the background color of the list from beige (#FFF5E7) to white (#FBFBFB). 2. Also, I need to update the read value of an Object from false to true using use ...

Issues with Angular 6 HTTPInterceptor interface in production environments

Currently, I am utilizing the HttpInterceptor interface to include an authorization header in HTTP requests. @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor( private localStorage: LocalStorageService, ...

Eliminate the usage of JSON.stringify in the Reducer function

I have a system where I store chat messages in a dictionary with the date as the key and a list of messages as the value. Whenever a new message is added, the following code snippet is executed. Is there a way to enhance the existing code to eliminate the ...

AngularJS/Angular 6 hybrid app encountering TS2430 error

My hybrid application, which combines AngularJS with Angular 6, is throwing a compilation error. The error is occurring in the file ~\node_modules\@angular\upgrade\static\src\common\angular1.d.ts. I'm seeing a t ...

The message "Expected a string literal for Angular 7 environment variables" is

I'm currently working on setting up different paths for staging and production environments in my Angular project, following the documentation provided here. I have a relative path that works perfectly fine when hardcoded like this: import json_data f ...

What is the best way to refresh information following its removal?

In my app, I have implemented a feature where posts are displayed as HTML cards using a component called PostList. Each card has a delete button to remove it from the list. The issue I am facing is that when I delete a card, it remains visible in the post ...

How can I utilize a variable as the value for ngClass in Angular 2?

Is there a way to use a variable in the ngClass value that gets added to the class list? I have a scenario where I have a set of image sprites, including a base sprite and an active state sprite with "-active" appended to the filename. I insert these sprit ...

Typescript error: Cannot assign type to argument

Exploring the world of typescript (2.5.2) and looking for clarity on why the first call works but the second one encounters an error: function printPerson(person: {firstName: string; lastName: string}): void{ console.log(person.firstName + " " + per ...

Unable to connect to a live Docker container using public DNS on an AWS EC2 instance

I have a requirement to host my Angular Webapp on an AWS EC2 instance. I followed the steps of creating a Dockerfile within my Angular project and deploying it onto the EC2 instance. Gitlab CI is responsible for building the Angular project and generating ...

Adjusting the width of a div element horizontally in Angular 4 and

As someone new to Angular 4, I've been attempting to create a resizable div (horizontally) without success. My goal is to be able to click and drag a grabber to resize the text area horizontally. However, in the example provided in the link below, the ...

Is it feasible to differentiate generic argument as void in Typescript?

One of the functions in my code has a generic type argument. In certain cases, when the context is void, I need to input 0 arguments; otherwise, I need to input 1 argument. If I define the function argument as context: Context | void, I can still add voi ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...

What is the correct way to convert a non-observable into an observable?

Can I convert a non-observable into an observable to receive direct image updates without having to refresh the page, but encountering this error: Type 'EntityImage[]' is missing the following properties from type 'Observable<EntityImage ...

Typescript type definitions - understanding inheritance

My typescript interface defines the structure of my database data as follows: interface Foo { bar: { fish: { _id: string, name: string, }[], }, starwars: string[], } I want to be able to reference specific parts of this inter ...

Is it possible for the NativeScript CLI to generate spec files automatically?

As I delved into NativeScript today, I couldn't help but notice that the tabbed template app it generated didn't come with spec files like those generated by Angular CLI. Is there a way to incorporate Karma and Jasmine into the app creation proce ...

The specified property type 'url' is not recognized on the provided 'Event' type

I came across the error message below [ts] Property type 'url' does not exist on type 'Event'. any This is the TypeScript (JavaScript) code snippet that I am using document.addEventListener("deviceready", onDeviceReady, false); ...

I'm encountering an issue with one of my routes not loading correctly in Angular 4 Universal

I have been working on implementing Universal and I believe I've made significant progress. My project is built on this seed. However, when I run "npm start", only the /about and /contact pages render successfully. The /home page does not render at al ...

Using TypeScript with React: The ideal type for utilizing the useLocation() function from the react-router-dom

I'm facing challenges finding the appropriate type for this specific scenario. Here is a simplified example of redirecting after login. The code snippet below is resulting in a compiler error: Property 'from' does not exist on type &apo ...

The 'filter' property is not found on the 'Observable<>' type

enter your code here... searchHospitals(term: string = null): Observable<Hospitals[]> { let hospitalsList = this.getHospitalsData(); if (term) { hospitalsList = hospitalsList.filter(hospital => hospital.name.toLocaleLowerCase() ...