简体   繁体   English

Angular Material Datepicker:如何过滤以便只允许数组中的日期?

[英]Angular Material Datepicker: How to filter so that only dates in an array are allowed?

I have an array of dates returned from an API.我有一个从 API 返回的日期数组。 For example, I might have an array entitled validDates that has all of the Mondays in September as their values.例如,我可能有一个名为validDates的数组,其中包含 9 月的所有星期一作为它们的值。 I would like to use the Material Datepicker filter to only allow date values in the array to be selected.我想使用 Material Datepicker过滤器只允许选择数组中的日期值。

Example Date Array示例日期数组

validDates = [
    Mon Sep 02 2019 00:00:00 GMT-0500 (Central Daylight Time),
    Mon Sep 09 2019 00:00:00 GMT-0500 (Central Daylight Time),
    Mon Sep 16 2019 00:00:00 GMT-0500 (Central Daylight Time),
    Mon Sep 23 2019 00:00:00 GMT-0500 (Central Daylight Time),
    Mon Sep 30 2019 00:00:00 GMT-0500 (Central Daylight Time)
]

Datepicker Filter (not working)日期选择器过滤器(不工作)

myFilter = ( d: Date ): boolean => {
    let dateOpen: boolean;
    for ( let x = 0; x < this.validDates.length; x++ ) {
      dateOpen = d.toString() === this.validDates[ x ].toString();
    }
    return dateOpen;
  }

The issue is it only returns the last date (Mon Sep 30 2019 00:00:00 GMT-0500 (Central Daylight Time)) as true so that only the 30th becomes selectable.问题是它只返回最后一个日期(2019 年 9 月 30 日星期一 00:00:00 GMT-0500(中央夏令时间))为true ,因此只有 30 日成为可选的。 I want each of the dates in the array to be selectable.我希望数组中的每个日期都是可选的。

How can I return true for each value in the array?如何为数组中的每个值返回true

To only allow dates within an array, the myFilter method may be defined as follows.为了只允许数组中的日期, myFilter方法可以定义如下。

myFilter = (d: Date): boolean => {
  // Only allow dates in `validDates`.
  return this.validDates.findIndex( (valid_date) => d.getTime() === valid_date.getTime()) > -1
}

See Stackblitz Demo查看Stackblitz 演示

To ignore the time component of the Date , see:要忽略Date的时间部分,请参阅:
Comparing date part only without comparing time in JavaScript仅比较日期部分而不比较 JavaScript 中的时间

Finally I found correct solution:最后我找到了正确的解决方案:

// The array of days of week to be available
const arr = [0, 3, 6];
this.expressSenderDate = (d: Date): boolean => {
    const day = d.getDay();
    // tslint:disable-next-line:align
    return arr.indexOf(day) !== -1;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM