![](/img/trans.png)
[英]How to change Angular Material Datepicker format in run-time
[英]How to change Angular Material Datepicker monthYearLabel format in run-time
我已按照以下问题的答案回答以下问题:
如何在运行时更改 Angular Material Datepicker 格式
这适用于在运行时更改日期的格式,但它也会更改日期选择器中的 monthYearLabel 格式,如下面的屏幕截图所示:
有没有办法在运行时更改 monthYearLabel 格式,使其与日期格式不同? 我希望它保留 MMM YYYY 的默认格式,如下所示:
有点晚了,但也许这可以帮助某人。
我已将名称设置为“monthYear”格式,并根据语言环境在运行时更改它:
import { formatDate } from '@angular/common';
import { Injectable } from '@angular/core';
import { NativeDateAdapter } from '@angular/material/core';
export const PICK_FORMATS = {
parse: { dateInput: { month: 'short', year: 'numeric', day: 'numeric' } },
display: {
dateInput: 'input',
monthYearLabel: 'monthYear', //{ year: 'numeric', month: 'short' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' }
}
};
@Injectable()
export class CustomDateAdapter extends NativeDateAdapter {
constructor() {
super(localStorage.getItem("locale") ?? "es-ES");
}
override format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
switch (this.locale) {
case 'es-ES':
return formatDate(date, 'dd/MM/yyyy', this.locale);
default:
return super.format(date, displayFormat);
}
} else if (displayFormat === 'monthYear') {
switch (this.locale) {
case 'es-ES':
return formatDate(date, 'MMM YYYY', this.locale);
default:
return super.format(date, displayFormat);
}
} else {
return super.format(date, displayFormat);
}
}
override parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
const year = Number(str[2]);
const month = Number(str[1]) - 1;
const date = Number(str[0]);
return new Date(year, month, date);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
override getFirstDayOfWeek(): number {
switch (this.locale) {
case 'es-ES':
return 1;
default:
return 0;
}
}
}
可能不是有史以来最好的 Angular / TS 代码,因为我对 Angular 还是很陌生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.