I have an ion-datetime
component where I need to restrict the selectable dates based on a range provided by the server. The issue arises because, on the initial render, the ion-datetime
component blocks all dates until the month is changed. This behavior occurs because the date ranges are fetched asynchronously, causing a delay in applying the restrictions.
<ion-datetime-button datetime="fecha-entrega"></ion-datetime-button>
<ion-modal [keepContentsMounted]="true">
<ng-template>
<ion-datetime
formControlName="fecha_entrega"
[isDateEnabled]="isDateWithinRange"
presentation="date"
id="fecha-entrega"></ion-datetime>
</ng-template>
</ion-modal>
import { Component, OnInit } from '@angular/core';
import { isWithinInterval, parseISO } from 'date-fns';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent implements OnInit {
dateRanges: Array<{ startDate: string; endDate: string }> = [];
constructor(private service: MyService) {}
ngOnInit() {
// Fetch date ranges from the server
this.service.getDateRanges().subscribe((dateRanges) => {
this.dateRanges = dateRanges;
});
}
// Function to validate if a date is within the allowed range
isDateWithinRange = (date: string): boolean => {
const parsedDate = parseISO(date);
return this.dateRanges.some(({ startDate, endDate }) =>
isWithinInterval(parsedDate, {
start: parseISO(startDate),
end: parseISO(endDate),
})
);
};
}