Julian Dave
Julian Dave

Reputation: 115

How do I exclude dates from angular material datepicker?

I am using Angular Material and I have a dynamic array of dates that I wish to exclude from my datepicker. In addition I am also trying to exclude Saturdays. How can I return multiple dates with my matDatepickerFilter? Keep in mind that I cant hardcode each item of the array individually because the array is fluid and will change both in its values and length after some time.

This is my HTML:

<mat-form-field style="text-align: center;"
[ngClass]="{'hideTitle': submitted && f4.houseNumber.errors?.required && f4.aptNumber.errors?.required}">
    <input matInput 
      [matDatepicker]="picker" 
      placeholder="Desired Delivery Date" 
      [matDatepickerFilter]="myFilter"
      formControlName="deliveryDate" 
      style="font-family: 'Open Sans Condensed', sans-serif; color:white;">
    <mat-datepicker-toggle matSuffix [for]="picker" 
    style="color:gold;outline:none;"></mat-datepicker-toggle>
    <mat-datepicker touchUi #picker disabled="false"></mat-datepicker>
</mat-form-field>

This is my array:

this.allDupedDates = [
  new Date('2019-04-30T00:00:00+02:00'),
  new Date('2019-04-28T00:00:00+02:00'),
  new Date('2019-05-21T00:00:00+02:00'),
  new Date('2019-05-23T00:00:00+02:00')
]

And this is the code:

myFilter = (d: Date): boolean => {
 const time = d.getTime();
 const day = d.getDay();
for (let i = 0; i < this.allDupedDates.length; i++) {
  var date = this.allDupedDates[i].getTime();
  return time !== date
}
return day !== 6;
}

Upvotes: 1

Views: 2379

Answers (1)

Jude Raj
Jude Raj

Reputation: 81

Filter code you need:

myFilter = (d: Date): boolean => {
  const day = d.getDay();
  const blockedDates = this.allDupedDates.map(d => d.valueOf());
  return (!blockedDates.includes(d.valueOf())) && day !== 6;
}

- Date objects can be easily compared with each other using the valueOf() method which returns their milliseconds since epoch.

Important tips to note:

  • Make sure the date objects you create in dupedDates are created in the same time zone where the filter is being executed. This ensures the timezones are the same and there will no timezone offset issues. Eg: 30th April 2019 00:00:00 changing to 29th April 2019 23:30:00.
  • The argument d:Date in the filter function will always be supplied with a date representing midnight in the client location's timezone. Eg: If the app is accessed from India: d will contain 29th April 2019 00:00:00 +05:30, 30th April 2019 00:00:00 +05:30, so on...

StackBlitz Example: https://stackblitz.com/edit/angular-datepicker-filter-so?file=app%2Fdatepicker-filter-example.ts

Upvotes: 1

Related Questions