我在材料日期选择器输入上设置日期格式时遇到问题,但他总是显示错误的格式。我已经按照docs中的方式进行了设置。 这是我在提供者中拥有的:
providers: [
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
],
其中“我的格式”是:
export const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'DD.MM.YYYY',
monthYearLabel: 'YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'YYYY',
},
}
这里的主要问题是
dateInput
格式不起作用,例如,我可以确认 monthYearLabel
,另外两个正在工作并响应编辑 MY_FORMATS
并在选择日期时正确显示在弹出窗口中,但输入中的日期始终强制使用 mm/dd/yyyy
格式,并且格式化起作用的唯一时间是当我将 dateInput
格式设置为如下所示时,对于任何其他格式,它仅在输入中显示 mm/dd/yyyy
,而不显示任何内容错误。
我还尝试创建一个自定义日期适配器类并使用它而不是 MomentDateAdapter,但同样的事情发生了,日期选择器弹出窗口中的所有标签的格式都正确,除了输入字段中的日期。
无论通过我尝试过的提供程序添加哪种格式方法,其行为都是相同的。如果我可以以某种方式附加到输入值更改,并在每次更改时手动格式化它,如果无法以这种方式解决它,那就太好了。所以非常欢迎任何建议
我不知道是否有可能存在某个全局区域设置干扰了这个或类似的事情。
有这个 stack 具有相同的行为,对我来说,正如他解释的那样,发生了同样的事情,如果我使用设置
dd/mm/yyyy
格式,它会正确显示,但仅当 dd
为 12 或更少时,如果天数为更高,它只在输入中显示 mm/dd/yyyy
格式,没有其他内容。
但我不能
解决方案1:
import { DateAdapter, MomentDateAdapter } from '@angular/material/core';
export class MyDateAdapter extends MomentDateAdapter {
constructor(locale: string, options: any) {
super(locale, options);
}
format(date: Date, displayFormat: string): string {
return moment(date).format(displayFormat);
}
parse(value: any, parseFormat: string): Date | null {
return moment(value, parseFormat).toDate();
}
}
providers: [
{
provide: DateAdapter,
useClass: MyDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
]
解决方案2:
import { MAT_DATE_LOCALE } from '@angular/material/core';
@NgModule({
providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'your-locale-code' },
// Other providers...
],
})
export class YourAppModule { }
解决方案3:
import { Component } from '@angular/core';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
@Component({
selector: 'app-your-component',
template: `
<mat-form-field>
<input matInput [matDatepicker]="picker" (dateInput)="onDateInput($event)">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
`,
})
export class YourComponent {
onDateInput(event: MatDatepickerInputEvent<Date>) {
if (event.value) {
// Format the date manually
const formattedDate = moment(event.value).format('DD.MM.YYYY');
// Update the input value with the formatted date
event.targetElement.value = formattedDate;
}
}
}