【问题标题】:How to disable Angular Material Datepicker dates from an array of dates?如何从日期数组中禁用 Angular Material Datepicker 日期?
【发布时间】:2020-05-19 11:12:33
【问题描述】:

我有一个日期数组,我想使用 Angular Material 的 Datepicker 禁用这些日期,我称之为 holidayList。

    holidayList: Date[] = [];
        this.holidayList: [
                    new Date("1/1/2020"),
                    new Date("1/20/2020"),
                    new Date("2/17/2020"),
                    new Date("5/25/2020"),
                    new Date("7/4/2020"),
                    new Date("9/7/2020"),
                    new Date("10/12/2020"),
                    new Date("11/11/2020"),
                    new Date("11/26/2020"),
                    new Date("12/25/2020")
                ]

阅读 Angular 的 Date validation 文档,我们可以像这样使用 [matDatepickerFilter]="myFilter"

HTML:

<mat-form-field class="example-full-width">
  <input matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

打字稿:

import {Component} from '@angular/core';

/** @title Datepicker with filter validation */
@Component({
  selector: 'datepicker-filter-example',
  templateUrl: 'datepicker-filter-example.html',
  styleUrls: ['datepicker-filter-example.css'],
})

export class DatepickerFilterExample {
  myFilter = (d: Date): boolean => {
    const day = d.getDay();
    // Prevent Saturday and Sunday from being selected.
    return day !== 0 && day !== 6;
  }
}

但是,提供的这个示例本质上是在说“提供一周中的日期不是 0 或 6 的所有日子”。对于如何实现日期列表并说“这是我们应该禁用的日期列表”,我有点困惑。

Link to Angular Material's example on Stackblitz

我知道关于这个主题有多个问题,但我遇到的所有答案都只涉及禁用一周中的某些天、几个月(例如禁用奇数月份)——本质上是禁用一种日期;在这种情况下,我想禁用硬编码日期,仅此而已。

【问题讨论】:

    标签: angular datepicker angular-material disabled-input


    【解决方案1】:

    Jedo 您需要更改 myFilter 函数,如果有效(在您的情况下,如果它不在数组 Holiday 中)返回 true,如果无效(当日期在数组 Holiday 中)返回 false。因此,您只需将函数替换为

      myFilter = (d: Date): boolean => {
        const time=d.getTime()
        return !this.holidayList.find(x=>x.getTime()==time)
      }
    

    注意:要在数组中查找我使用 getTime 转换您的日期数组,如果您将数组直接存储为时间会更有效

        this.holidayList=[new Date("1/1/2020").getTime(),
                          new Date("1/20/2020").getTime(),
                          ...  
                         ]
    

    还有你的功能

     myFilter = (d: Date): boolean => {
        const time=d.getTime()
        return !this.holidayList.find(x=>x==time)
      }
    

    注意2:(这不避免用户可以手动输入无效日期,因此您需要制作自定义验证器来检查日期是否有效

    validateDate()
    {
       return (control:FormControl)=>{
           const time=control.value.getTime();
           return this.holidayList.find(x=>x==time)?{error:'we are on holidays'}:null
       }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多