Search code examples
angularlocaleflatpickr

Error when loading locale on Angular using angularx-flatpickr


Added the locale to directive on angular component:

<input
type="text"
name="date"
mwlFlatpickr
[altInputClass]="'form-control'"
[(ngModel)]="post.date"
[altInput]="true"
[inline]="true"
[dateFormat]="'d.m.y'"
[locale]="'Portuguese'"
[defaultValue]="'today'"
[convertModelValue]="true">

When trying to load the locale, the erro is returned:

Error: flatpickr: invalid locale Portuguese

at setupLocale (flatpickr.js:1910) at init (flatpickr.js:581) at FlatpickrInstance (flatpickr.js:2419) at _flatpickr (flatpickr.js:2438) at flatpickr (flatpickr.js:2463) at FlatpickrDirective.push../node_modules/angularx-flatpickr/fesm5/angularx-flatpickr.js.FlatpickrDirective.ngAfterViewInit (angularx-flatpickr.js:295) at callProviderLifecycles (core.js:22416) at callElementProvidersLifecycles (core.js:22390) at callLifecycleHooksChildrenFirst (core.js:22380) at checkAndUpdateView (core.js:23316)


Solution

  • On your module.ts file, import all necessary files, create a function named flatpickrFactory, and import the language correspondent to your language (All languages files are here)

    import { FlatpickrModule, FLATPICKR } from 'angularx-flatpickr';
    import flatpickr from 'flatpickr';
    import { Portuguese } from 'flatpickr/dist/l10n/pt';
    
    export function flatpickrFactory() {
      flatpickr.localize(Portuguese);
      return flatpickr;
    }
    

    Now, on your component.ts import flatpickrFactory(); to your ngOnInit() method.

    ngOnInit() {
      flatpickrFactory();
    
      // Your other logic here...
    } 
    

    And in your component.html (templateUrl), add the directive, like this example:

    <input 
      type="text" 
      mwlFlatpickr 
      [(ngModel)]="selectedDate" 
      [altInput]="true" 
      [dateFormat]="'d.m.y'"
      [locale]="'Portuguese'"
      [convertModelValue]="true">