How to enable only specific dates in Angular 5?

坚强是说给别人听的谎言 提交于 2020-01-21 19:50:25

问题


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",
      }]

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>

In my Component.ts file:

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

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

}

Can anyone help on this?


回答1:


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


来源:https://stackoverflow.com/questions/48546547/how-to-enable-only-specific-dates-in-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!