Reputation: 115
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
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:
StackBlitz Example: https://stackblitz.com/edit/angular-datepicker-filter-so?file=app%2Fdatepicker-filter-example.ts
Upvotes: 1