Refining dates in the Angular Material Calendar by utilizing two lists obtained from asynchronous sources

I am facing a challenge with disabling certain dates on a Material Calendar. These dates are sourced from two different places. The first set of dates come from within an object (camper) that is provided as input. The second set comes from an API call that retrieves a list of bookings based on the camper ID. While the first set of dates is read and disabled without any issues, the problem arises when dealing with the API call. It seems like the filter does not wait for the data to be fully fetched before applying the disabling logic. I have tried various methods such as promises, async/await, and fork join but none seem to make the filter wait or disable any dates at all.

For the specific camper in question, the expected outcome would be 2 periods of disabled dates on the calendar:

  • 12/06 to 15/06 (blocked dates) <- visible
  • 21/06 to 24/06 (booked dates) <- not visible

I need assistance in finding a way for the filter to wait until the complete list of dates is obtained before applying the disable functionality.

component.html

<div class="calendar-wrapper">
<mat-calendar
#calendar
(monthSelected)="handleMonthSelected($event)"
(selectedChange)="onSelect($event)"
[comparisonStart]="this.selectedDateRange.start"
[comparisonEnd]="this.selectedDateRange.end"
[selected]="selectedDateRange"
[dateFilter]="blockedDatesFilter"
>
</mat-calendar>
</div>

component.ts

export class CamperBookingDetailsComponent implements AfterContentInit {
@Input() camper!: Camper;
@ViewChild('calendar') calendar!: MatCalendar<Date>;

blockedDates = (): Date[] => {
    let tempBlockedDates: Date[] = [];
    Object.entries(this.camper.difPrizes).forEach(([key, value]) => {
        if (value === 0) {
            tempBlockedDates.push(new CamperDate(new Date(key)));
        }
    });

    this._bookingService.getBookings$({"camperId": this.camper._id}).subscribe(bookings => {
        bookings.forEach(booking => {

          this.getDates(new Date(booking.startDate), new Date(booking.endDate)).forEach(date => {
            tempBlockedDates.push(date);
          });
        });
    });
    return tempBlockedDates;
}
blockedDatesFilter = (d: Date): boolean => {
console.log(this.blockedDates());
const time = d.getTime();
return !this.blockedDates().find(x => x.getTime() == time);
};

constructor(private _renderer: Renderer2, private _bookingService: BookingService) {}
}

I also attempted using asynchronous code like below. However, it was unsuccessful as the Material Calendar does not support (d: Date) => Promise.

blockedDates = async (): Promise<Date[]> => {
let tempBlockedDates: Date[] = [];
Object.entries(this.camper.difPrizes).forEach(([key, value]) => {
if (value === 0) {
tempBlockedDates.push(new CamperDate(new Date(key)));
}
});

await this._bookingService.getBookings$({"camperId": this.camper._id}).subscribe(bookings => {
bookings.forEach(booking => {
this.getDates(new CamperDate(booking.startDate), new CamperDate(booking.endDate)).forEach(date => {
tempBlockedDates.push(date);
});
});
});

return tempBlockedDates;
}
blockedDatesFilter = async (d: Date): Promise<boolean> => {
console.log(this.blockedDates());
const time = d.getTime();
const blockedDates = await this.blockedDates();
return !blockedDates.find(x => x.getTime() == time);
};

Console log excerpt from within

blockedDatesFilter = (d: Date): boolean
:

(4) [Sun Jun 12 2022 00:00:00 GMT+0200 (Central European Summer Time), Mon Jun 13 2022 00:00:00 GMT+0200 (Central European Summer Time), Tue Jun 14 2022 00:00:00 GMT+0200 (Central European Summer Time), Wed Jun 15 2022 00:00:00 GMT+0200 (Central European Summer Time)]
0: Sun Jun 12 2022 00:00:00 GMT+0200...

Material Calendar Screenshot: Material Calendar

Answer №1

I can't provide a specific solution without seeing your async code.

Did you attempt something like this?

async function checkBlockedDates(dateToCheck) {
   console.log(getBlockedDates());
   const time = dateToCheck.getTime();
   const blockedDates = await getBlockedDates();
   return !blockedDates.find(blockedDate => blockedDate.getTime() === time);
}

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

The interface does not allow properties to be assigned as string indexes

Below are the interfaces I am currently working with: export interface Meta { counter: number; limit: number; offset: number; total: number; } export interface Api<T> { [key: string]: T[]; meta: Meta; // encountered an error here } I h ...

Efficiently setting up the system-config.ts to incorporate additional libraries such as angular2-material2 package in Angular2

I'm feeling a bit lost trying to understand the configuration of system-config.ts. Currently, I am attempting to integrate material2 code into my Angular quick start bundle, but I'm facing some issues. On the material2 GitHub page, it instructs ...

Innovative techniques for class manipulation

Is there a way to implement type checking when extending a class with dynamic methods? For example, if you want to add methods to a class based on options provided to the constructor. This is a common scenario in plain JavaScript. const defaults = { dyn ...

Can a File Object be transmitted to an AWS Lambda function via API Gateway using JavaScript?

Can a JavaScript File Object be passed from a browser to AWS Lambda via API Gateway (ultimately to S3)? I am working with TypeScript and React. Environment Frontend TypeScript React AWS Amplify (for API module) Backend(AWS Lambda) Node.js Expecta ...

What methods does Angular use to manipulate the DOM?

Picture this scenario... <ul> <li *ngFor="random"></li> </ul> ...with a MutationObserver monitoring its changes: observer.observe(this.el, { characterData: true, subtree: true }); Whenever this template renders, the observer ...

This TypeScript error indicates that the variable may be undefined (Error code: 18048)

One of the challenges I encountered in my Angular project was with an interface defined in userinterface.ts export interface Done { wordlen: number; word: string; }; I utilized this interface to populate an array like so donearr: Done[] = []; ...

Creating a Route in Angular 2 for a Component other than the one initialized with the bootstrap function

I am currently in the process of working on a project involving Angular2. If you are interested in understanding why I need to do what I am about to explain, please take a look at this issue. The main component in my project is called AppComponent and it ...

Error in Angular: trying to access property 'genre' of an undefined object

I am currently developing a simple app inspired by a tour of heroes (official angular tutorial). However, I have encountered an issue that I cannot seem to resolve, possibly due to my lack of understanding in basic programming concepts. Here is the code s ...

Encountering issues with npm install @angular/material for installing angular2 material package

Attempting to install angular2 material using the command npm install @angular/material: [xxx@Latitude-E5550 quickstart]$ npm install @angular/material [email protected] /home/xxx/quickstart └── @angular/[email protected] npm ...

Creating an endless scrolling feature with Ionic 3

My tech stack includes symfony3 and FosRestBundle for the backend, and Ionic 3 for the frontend development. While attempting to implement an InfiniteScroll feature following the Ionic documentation, I encountered an issue where only the loading text and ...

Elements on border failing to display appropriately

Why is the border of the drop-down not displaying correctly? It appears that other components are overlapping, but I am unsure how to resolve this issue. <div class="ui-g"> <div class="ui-g-6 ui-md-6 ui-fluid"> <label for="">St ...

Can Angular dynamically obtain the current system time without relying on a backend service?

Is there a way to dynamically display the current system time on a webpage using Angular without having to manually refresh the page? I understand that utilizing Date() can provide the current time, but it may not necessarily be synced with the system tim ...

Navigating with Angular 4's router and popping up modals

I have an Angular 4 SPA application that utilizes the Angular router. I am looking to create a hyperlink that will open a component in a new dialog using Bootstrap 4. I am able to open modal dialogs from a function already. My question is, how can I achi ...

Using the currency pipe with a dynamic variable in Angular 2

My application utilizes CurrencyPipe, The current implementation is functional, <div class="price">{{123 | currConvert | currency:'USD':true:'3.2-2'}}</div> Now, I need to dynamically pass the currency from a model varia ...

Tips for utilizing intellisense from monaco.d.ts

Is there a way for me to incorporate monaco.d.ts in order to utilize intellisense with the monaco-editor package? I've recently integrated this package into a JavaScript project and everything is functioning properly. However, as I transition to Type ...

Issues arising with utilizing Github for hosting Angular applications

After developing a site with Angular, everything was running smoothly on my local host. However, when I decided to host the site on GitHub, two errors appeared. You can access my site through this link: Here is a screenshot of the errors encountered [1]: ...

Unable to detect keyup.enter event on iOS keyboard

After developing my app in the Ionic framework + Angular, I encountered an issue with binding the (keyup.enter) event to input functionality. It seems to be working flawlessly on older versions of iOS devices like (OS 12.5.4), but not on the latest version ...

Unlocking the union of elements within a diverse array of objects

I have an array of fields that contain various types of input to be displayed on the user interface. const fields = [ { id: 'textInput_1', fieldType: 'text', }, { id: 'selectInput_1', fieldType: 'sel ...

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

Optimizing your data layer in Angular2: A Guide to Best Practices

As a newcomer to Angular2, I am diving into hands-on learning. My current project involves building multiple views with parent components, child components, and database services. After successfully creating one view, I am now gearing up to implement other ...