我有一个非常相似的问题。我使用 MomentDateAdapter 和自定义指令解决了它。我采取的步骤:
- 安装 @angular/material-moment-adapter 和 moment.js
- 添加日期格式配置:
export const DATE_FORMATS = {
parse: {
dateInput: ['MMM DD yyyy']
},
display: {
dateInput: 'MMM DD yyyy',
monthYearLabel: 'MMM yyyy',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM yyyy',
},
};
第一个'dateInput'很重要你应该如何输入日期(例如使用键盘)才能成功解析。第二个“dateInput”很重要,用什么格式来显示日期。
- 定义提供者:
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]},
{ provide: MAT_DATE_FORMATS, useValue: DATE_FORMATS }
- 创建自定义指令:
import {
Directive,
EventEmitter,
HostListener,
Input,
Output,
} from '@angular/core';
@Directive({
selector: '[setOutputDateFormat]',
})
export class DateFormatDirective {
@Input('setOutputDateFormat')
inputFormat = null;
@Output()
dateChangeWithFormat = new EventEmitter<string>();
constructor() {}
@HostListener('dateChange', ['$event'])
onDateChange(event: any) {
const dateFormatted = event.value.format(this.inputFormat);
this.dateChangeWithFormat.emit(dateFormatted);
}
}
Directive 监听 'dateChange' 事件,event.value 属性应该在 moment 对象中包含日期(因为我们在开始时切换到 MomentDateAdapter),因此指令将格式切换为所需的格式并以所需的格式触发自定义事件
- 最后使用模板中的指令在“outputDateFormat”属性中提供自定义格式:
<mat-form-field>
<input
matInput
[setOutputDateFormat]="outputDateFormat"
[matDatepicker]="dp"
placeholder="Choose a date"
(dateChangeWithFormat)="updateDOB($event)"
/>
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker touchUi #dp disabled="false"></mat-datepicker>
</mat-form-field>
此处示例:https://stackblitz.com/edit/angular-ivy-beufcw?file=src/app/app.component.ts
现在看来 moment.js 项目具有遗留状态,因此更好的解决方案是切换到 luxon 日期适配器(应该不难,因为 luxon 是 moment.js 的继任者)