Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Language switch for Angular Material datepicker in lazy-loaded module

How can I switch the language of my material datepickers across the whole application (i.e. for datepickers in eagerly and lazy-loaded components)?

I created a stackblitz example demostrating my problem:

https://stackblitz.com/edit/angular-4cu4cb

As soon as the language is changed in the eagerly- or lazy-loaded component, I would like to change the language for both the datepickers. Unfortunately, this does not work yet.

How can I achieve this?

like image 841
René Winkler Avatar asked Jun 03 '18 12:06

René Winkler


1 Answers

I corrected your example on stackBlitz it seems the displayDormat is an object not your locale format, you can access this.locale in the adapter to have the right format for the dates.

if (this.locale === 'myCustomFormat') {      
      const day = date.getUTCDate();
      const month = date.getUTCMonth() + 1;
      const year = date.getFullYear();

      // Return the format as per your requirement
      return `${day}.${month}.${year}`;
    } else {
      // Refer to the standard formatting of the NativeDateAdapter.
      return super.format(date, displayFormat);
    }

For the syncking problem between the components I will suggest a service injected on the root of the app which holds your locale into an observable and the date adapter will read the value from that observable and formats the date corespondigly. I will have a look later on that also in hard to make the sync on stackblitz :D here is your example changed and I hope it gives you an idea on how to sync the services I didn't manage to make appLocale const a service which is injectable. Cause NativeDateAdapter constructor has some dependencyes on material design and your class is not injectable you can correct them to be angular services and inject all your params together with the observable and make the subscription in the constructor.

Please have a look I hope this is what you need.

like image 138
Nicu Avatar answered Nov 16 '22 07:11

Nicu