2
votes

I'm developing an angular 7 application with lazy loaded modules. I'm using angular material components as well. I would like to localize and support multiple locales in datepicker component.

I would like to change it globally for the whole application when application language changes. It may be done via DateAdapter.setLocale method. However the problem is that if I change it on my root module then it does not change in lazy loaded modules.

Yes, lazy loaded modules have their injector and receive their DateAdapter, where locale is not set to the correct one.

How to achieve that DateAdapter is singleton in the whole app? For other modules there is a forChild() vs forRoot() API, but not for datepicker module.

1
you can use providedIn: 'root' in your singleton service then, whenever you need to use it, use @Inject(DateAdapter) so that angular is aware that it needs to inject the service instance.briosheje
@briosheje hmm, ok but if I undertand it correctly, then this service should be used in every Lazy Loaded modules to set dateAdapter locale. Am I right? I would like to inject DateAdapter in my root component and call one time setLocale() and with that change locale in every Lazy Loaded module.thadam

1 Answers

2
votes

The problem for me was that I imported my DateAdapter in my SharedModule and then imported that SharedModule in my AppModule and in other LazyModules.


To make the DateAdapter a singleton service you should provide the DateAdapter you're using only once at root level in your application and not at root level and in LazyModules.

To do so make sure that you import the module that provides the DateAdapter, e.g. MatNativeDateModule, only in your AppModule (or another root module thats imported only once like a CoreModule). Don't import MatNativeDateModule in multiple modules or in a module that's imported multiple times like a SharedModule.

import { MatNativeDateModule } from '@angular/material/core'

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    MatNativeDateModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Then you can set the locale in your AppComponent.

export class AppComponent implements OnInit {
  constructor(private dateAdapter: DateAdapter<Date>) {}

  ngOnInit(): void {
    this.dateAdapter.setLocale('en')
  }
}

And the same DateAdapter with the set locale will be injected in your LazyModules.