'RangeError: locale must contain localize property when using Angular material date picker with date fns

I have the following configuration on the 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 { }

when I use the component on app.component.html I get the error ERROR RangeError: locale must contain localize property.

I tried the component with just the MatNativeDateModule and removed these lines

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

and it works, since now it's using the MatNativeDateModule.

Things that I have tried:

  • Added the MatNativeDateModule along with the MatDateFnsModule.
  • Used the deps option for the injection of MAT_DATE_LOCALE

Thanks



Solution 1:[1]

I was able to solve this by setting locale in the constructor. Not really clean, but fixes the issue.

import { DateAdapter } from '@angular/material/core';
import { enUS } from 'date-fns/locale';

export class DatepickerComponent {
  constructor(private _adapter: DateAdapter<any>) {
    this._adapter.setLocale(enUS);
  }
}

Solution 2:[2]

After looking through the code from the date-fns adapter, it is required to specify MAT_DATE_LOCALE to the selected date-fns locale.

// app.module.ts

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

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

Note: The locale on useValue is not a string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jamespsterling
Solution 2