如何在Angular 5中仅启用特定日期? [英] How to enable only specific dates in Angular 5?

查看:58
本文介绍了如何在Angular 5中仅启用特定日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组日期,我只想启用<mat-datepicker>中的那些日期.

I have set of dates and I want to enable only those dates in <mat-datepicker>.

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

这是我的html代码:

This is my html code:

<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()

}

有人可以帮忙吗?

推荐答案

您将需要一个自定义验证器.可在此处找到更多详细信息: https://material.angular.io/components/datepicker/overview#date-validation

You are going to need a custom validator. More details can be found here: https://material.angular.io/components/datepicker/overview#date-validation

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

Essentially you give a function that takes in a date and returns a boolean indicating whether that date is valid. In your case you want to in your controller check if the given date is a member of your list. Here is a basic implementation:

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()];
  }
}

这篇关于如何在Angular 5中仅启用特定日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆