Pre filling the [matDatepickerFilter] makes the form invalid

Discussão em 'Angular' iniciado por Bjorn, Abril 13, 2025.

  1. Bjorn

    Bjorn Guest

    I want to disable dates that have selected already in the previous inputs. Field in the UI

    Here's how I'm doing it currently:

    disabledDates: Date[] = [];


    and inside my ngOnChanges() function I'm pushing the data from the backend to my form:

    this.location.holidayHours.map((holiday: any, index) => {
    if (holiday.date && holiday.from) {
    holiday.date = moment(`${holiday.date} ${holiday.from}`).tz('UTC').format();
    }

    this.holidayHoursFormArray.push(
    new UntypedFormGroup({
    date: new UntypedFormControl(holiday.date, [Validators.required]),
    type: new UntypedFormControl(holiday.type),
    from: new UntypedFormControl(holiday.from),
    to: new UntypedFormControl(holiday.to)
    })
    );
    this.day_type.types[ 7+index] = holiday.type;
    this.disabledDates.push(new Date(holiday.date));
    });


    The UI section looks like this in the template:

    <input
    matInput
    [matDatepickerFilter]="filterHolidayDates"
    class="datepicker"
    [matDatepicker]="picker"
    placeholder="Choose a date"
    formControlName="date"
    (ngModel)="(hoursFormGroup.value.holidayHours.date)"
    readonly
    (dateChange)="onDateSelected($event.value, i)"
    />
    <div class="mat-form-field-suffix flex">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    </div>
    <mat-datepicker #picker></mat-datepicker>


    and this is how I filter the dates:

    filterHolidayDates = (date: Date | null): boolean => {
    if (!date) return true; // Handle null case

    // Disable past dates
    if (date < this.today) {
    return false;
    }

    // Disable specific disabled dates
    return !this.disabledDates.some(d =>
    d.getDate() === date.getDate() &&
    d.getMonth() === date.getMonth() &&
    d.getFullYear() === date.getFullYear()
    );
    };


    After pre-filling the form with dates from the location.holidayHours, the holidayHoursFormArray's status becomes "INVALID". And when I console.log the form it shows

    errors:
    matDatepickerFilter: true


    Is there a way to disable dates in the date picker during form initialization without including them in the validation?

    Continue reading...

Compartilhe esta Página