首页 > 解决方案 > Angular 7 Mat datepicker - 如何将月份名称从短更改为长:

问题描述

我需要帮助,尝试了很多东西但没有帮助。我使用 Angular 7 Mat datepicker,并且真的很想知道如何将月份的名称从短更改为长:

这些是月份的默认短名称

在此先感谢您的帮助。

标签: angulardatepicker

解决方案


据我所知,您可以使用日期选择器组件配置的唯一格式是:https ://material.angular.io/components/datepicker/overview#accessibility

@NgModule({
  imports: [MatDatepickerModule, MomentDateModule],
  providers: [
    {
      provide: MAT_DATE_FORMATS,
      useValue: {
        parse: {
          dateInput: ['l', 'LL'],
        },
        display: {
          dateInput: 'L',
          monthYearLabel: 'MMM YYYY',
          dateA11yLabel: 'LL',
          monthYearA11yLabel: 'MMMM YYYY',
        },
      },
    },
  ],
})
export class MyApp {}

ref: MAT_DATE_FORMATS 定义/字段含义

如果您想知道这些来自哪里或语法是如何完成的,请查看此链接:https ://momentjs.com/docs/#/displaying/format/

如果您仍然想尝试更改它,您可以尝试从 moment.js 覆盖monthShort,这是使用此组件工作的库:

moment.updateLocale('en', {
    months : [
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"
    ]
});

考虑到您在上面看到的这个标签适用于语言环境

  constructor(@Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string) {
    super();
    this.setLocale(dateLocale || moment.locale());
  }

  setLocale(locale: string) {
    super.setLocale(locale);

    let momentLocaleData = moment.localeData(locale);
    this._localeData = {
      firstDayOfWeek: momentLocaleData.firstDayOfWeek(),
      longMonths: momentLocaleData.months(),
      shortMonths: momentLocaleData.monthsShort(),
      dates: range(31, (i) => this.createDate(2017, 0, i + 1).format('D')),
      longDaysOfWeek: momentLocaleData.weekdays(),
      shortDaysOfWeek: momentLocaleData.weekdaysShort(),
      narrowDaysOfWeek: momentLocaleData.weekdaysMin(),
    };
  }

推荐阅读