如何在Angular 5中仅启用特定日期?

时间:2018-01-31 16:08:15

标签: datepicker angular5

我有一组日期,我只想在<mat-datepicker>中启用这些日期。

"ListOfDates": [
      {
         "startDate": "2018-01-01T08:00:00"
      },
      {
         "startDate": "2018-01-02T08:00:00"
      },
      {
        "startDate": "2018-01-03T09:00:00",
      }]

这是我的HTML代码:

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

在我的Component.ts文件中:

@Component({...})
export class SomeComponent.ts {

    dateFilter = (date: Date) => date.getDate()

}

有人可以为此提供帮助吗?

2 个答案:

答案 0 :(得分:2)

您将需要一个自定义验证器。更多细节可以在这里找到:https://material.angular.io/components/datepicker/overview#date-validation

基本上,您提供一个接受日期并返回一个布尔值的函数,该布尔值指示该日期是否有效。在您的情况下,您希望在控制器中检查给定日期是否是列表的成员。这是一个基本的实现:

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>

TS:

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 {
  validDates = {
    "2018-01-01T08:00:00": true,
    "2018-01-02T08:00:00": true
  }

  myFilter = (d: Date): boolean => {
    // Using a JS Object as a lookup table of valid dates
    // Undefined will be falsy.
    return validDates[d.toISOString()];
  }
}

答案 1 :(得分:1)

myFilter = (d: Date): boolean => {
  let enableFlag = false;
  this.ListOfDates.some((date) => {
    if (date.startDate === d) { // You can use any other comparison operator used by date object
      enableFlag = true;
      return true;
    }
  })
  return enableFlag;
}

注意:您将必须将ListOfDates中的d和日期格式化为您选择的标准格式