角材料日期选择器禁用年份选择 [英] Angular Material Date picker disable the year selection

查看:50
本文介绍了角材料日期选择器禁用年份选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在角度材质日期选择器中禁用年份选择.

I am trying to disable the year selection in angular material date picker.

我已经创建了自定义本机日期适配器,以在从日期选择器中选择日期时显示日期.在这种情况下,年份是禁用的,因此用户无法更改年份.

I've created custom native date adapter to dispaly the date when selected from the date picker. In this case year is disable so user can't able to change the year.

从'@ angular/material'导入{NativeDateAdapter};

import { NativeDateAdapter } from '@angular/material';

export class AppDateAdapter extends NativeDateAdapter {
  months = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec'
  ];

  format(date: Date, displayFormat: Object): string {
    if (displayFormat === 'input') {
      const day = date.getDate();
      const month = this.months[date.getMonth()]; // date.getMonth() + 1;
      const year = date.getFullYear();
      let days: any;
      if (day <= 9) {
        days = '0' + day;
      } else {
        days = day;
      }
      return `${days}` + '-' + `${month}` + '-' + `${year}`;
    }
    return date.toDateString();
  }
}

推荐答案

来自角度材料文档;

与任何标准< input> 一样,可以通过添加disabled属性来禁用日期选择器输入.默认情况下,< mat-datepicker> < mat-datepicker-toggle> 将从< input> ,但是可以通过在datepicker或toggle元素上设置disabled属性来覆盖此属性.如果要禁用文本输入但允许通过日历进行选择,反之亦然,这很有用.

As with any standard <input>, it is possible to disable the datepicker input by adding the disabled property. By default, the <mat-datepicker> and <mat-datepicker-toggle> will inherit their disabled state from the <input>, but this can be overridden by setting the disabled property on the datepicker or toggle elements. This can be useful if you want to disable text input but allow selection via the calendar or vice-versa.

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp1" placeholder="Completely disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
    <mat-datepicker #dp1></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp2" placeholder="Popup disabled">
    <mat-datepicker-toggle matSuffix [for]="dp2" disabled></mat-datepicker-toggle>
    <mat-datepicker #dp2></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp3" placeholder="Input disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp3"></mat-datepicker-toggle>
    <mat-datepicker #dp3 disabled="false"></mat-datepicker>
  </mat-form-field>
</p>

有关更多信息,请参见:

for further information please see:

https://material.angular.io/components/datepicker/overview

这篇关于角材料日期选择器禁用年份选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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