RangeError:将 Angular 材料日期选择器与日期 fns 一起使用时,区域设置必须包含 localize 属性

2024-04-27

我在 app-module.ts 上有以下配置

import { ReactiveFormsModule } from '@angular/forms';
import { DateFnsAdapter, MatDateFnsModule } from '@angular/material-date-fns-adapter';
import { DateAdapter, MatDateFormats, MatNativeDateModule, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from "@angular/common";


let matLocale = "en-GB"
let dateInput = "DD/MM/YYYY";

export const MY_DATE_FORMATS: MatDateFormats = {
  parse: {
    dateInput: dateInput,
  },
  display: {
    dateInput: dateInput,
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY'
  },
};

@NgModule({
    declarations: [
      AppComponent
    ],
    imports: [
      BrowserModule,
      CommonModule,
      MatDateFnsModule,
      MatDatepickerModule
    ],
    providers: [
      {
        provide: MAT_DATE_LOCALE,
        useValue: matLocale
      },
      { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS },
      {
        provide: DateAdapter,
        useClass: DateFnsAdapter,
        // deps: [MAT_DATE_LOCALE] // this can be optional since I already provide a value, but I put it for example purposes
      }
    ],
    bootstrap: [
      AppComponent
    ]
)}

export class AppModule { }

当我使用该组件时app.component.html我收到错误ERROR RangeError: locale must contain localize property.

我尝试了该组件MatNativeDateModule并删除了这些行

    {
      provide: DateAdapter,
      useClass: DateFnsAdapter,
      // deps: [MAT_DATE_LOCALE]
    }

and it works,因为现在它正在使用MatNativeDateModule.

我尝试过的事情:

  • 添加了MatNativeDateModule随着MatDateFnsModule.
  • 使用了deps注射选项MAT_DATE_LOCALE

Thanks


从 date-fns 适配器查看代码后,需要指定MAT_DATE_LOCALE到选定的 date-fns 区域设置。

// app.module.ts

import { es } from 'date-fns/locale';

providers: [
    {
        provide: MAT_DATE_LOCALE,
        useValue: es,
    },
],

注意:区域设置useValue不是一个字符串。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RangeError:将 Angular 材料日期选择器与日期 fns 一起使用时,区域设置必须包含 localize 属性 的相关文章

随机推荐