我正在使用Angular Material,并且有一个动态数组,希望将其从日期选择器中排除。此外,我还试图排除星期六。如何使用matDatepickerFilter返回多个日期? 请记住,我无法对数组的每个项目分别进行硬编码,因为该数组是可变的,一段时间后其值和长度都会改变。
这是我的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.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')
]
这是代码:
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;
}
答案 0 :(得分:1)
您需要的过滤代码:
myFilter = (d: Date): boolean => {
const day = d.getDay();
const blockedDates = this.allDupedDates.map(d => d.valueOf());
return (!blockedDates.includes(d.valueOf())) && day !== 6;
}
-使用valueOf()方法可以轻松地比较日期对象,该方法返回自历元以来的毫秒数。
要注意的重要提示:
StackBlitz示例:https://stackblitz.com/edit/angular-datepicker-filter-so?file=app%2Fdatepicker-filter-example.ts