通过键盘输入的角度材质日期选择器格式仅适用于 Chrome



我正在使用Angular Material提供的日期选择器组件,遇到了以下问题:如果我想输入日期而不是按以下格式选择:"2019.12.20",那么它仅适用于Chrome。我在 Edge 和 Firefox 上尝试过,如果我使用这种格式,日期值为 null。但是,如果我使用"-"或"/"而不是" . ",例如"2019-12-20",那么它可以毫无问题地工作。

我已将提供程序设置为:

providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'hu' },
{ provide: DateAdapter, useClass: AppDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS }            
]

我的日期适配器如下:

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

export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${year}.${month}.${day}`;
}
return date.toDateString();
}
}
export const APP_DATE_FORMATS =
{
parse: {
dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'numeric' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' },
}
};

知道出了什么问题吗?如果您需要有关此问题的更多信息,请告诉我。

似乎问题出在 Edge 和 IE 中的 NativeDateAdapter 上。尝试改用 MomentDateAdapter。

所以快速解释: 在提供程序中使用 MomentDateAdapter,如下面的代码中所述:

TS 文件

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import * as _moment from 'moment';
const moment = _moment;
export const MY_FORMATS = {
parse: {
dateInput: ['YYYY.MM.DD', 'YYYY-MM-DD', 'YYYY/MM/DD', 'YYYY MM DD']
},
display: {
dateInput: 'YYYY MMM DD',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
/** @title Datepicker with custom formats */
@Component({
selector: 'datepicker-formats-example',
templateUrl: 'datepicker-formats-example.html',
styleUrls: ['datepicker-formats-example.css'],
providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'hu' },
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
export class DatepickerFormatsExample {
date = new FormControl(moment());
}

网页文件

<mat-form-field>
<input matInput [matDatepicker]="dp" placeholder="Verbose datepicker" [formControl]="date">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp></mat-datepicker>
</mat-form-field>

在上面的示例中,日期字段接受以下格式作为输入['YYYY.MM.DD', 'YYYY-MM-DD', 'YYYY/MM/DD', 'YYYY MM DD'],然后将以这种格式显示它们YYYY MMM DD

最新更新