angularmat-datepicker

Disable past dates except for single date in mat-datepicker Angular


I want disable past dates except 13-04-2023 in mat-datepicker. Currently i create datepicker with custom filter function to disable past dates except for 13-04-2023 but this dont working:(

  myFilter = (date: Date | null): boolean => {
    const today = new Date()
    if(!date) { return false }

    return date >= today && !this.isSameDate(date)
  };

  isSameDate(date1: Date) {
    return date1.toDateString() === this.excludedDate.toDateString()
  }

  this.excludedDate = new Date(2023, 3, 13)


  <input matInput formControlName="effectiveDate" [matDatepicker]="pickerFrom" [matDatepickerFilter]="myFilter"/>
  <mat-datepicker-toggle matIconSuffix [for]="pickerFrom"></mat-datepicker-toggle>
  <mat-datepicker #pickerFrom ></mat-datepicker>

I cant choose past date, so its nice but i also can't pick 13-04-2023

enter image description here

Whats is the fix for this?


Solution

  • The matDatepickerFilter predicate should return true for dates that are enabled.

    Your predicate says "date have to be greater or equal than today AND not equal excludedDate". Since your excludedDate is in the past, those two parts are mutually exclusive.

    I assume you were aiming for something like:

    return date >= today || this.isSameDate(date)