core icon indicating copy to clipboard operation
core copied to clipboard

Why should I describe the default localization in each component, even using a smart component?

Open splincode opened this issue 8 years ago • 2 comments

If for each component I do not specify this code: https://stackblitz.com/edit/angular-nmzvpj?file=app%2Fapp.component.html

this.translateService.setDefaultLang('<your_lang_here>')
this.translateService.use('<your_lang_here>')

My code will not be able to use the translation in the template...

image

Expected/desired behavior

Truth is easily solved at the level of one component: https://stackblitz.com/edit/angular-hhdsnl?file=app%2Fapp.component.html

image

But it's very inconvenient and it's not obvious why you can not specify a default language when declaring a module?

image

Please tell us about your environment:

  • ngx-translate version: 9.0.2
  • Angular version: 5.1.3

splincode avatar Jan 09 '18 19:01 splincode

Your first StackBlitz does not exist anymore, but with the information I have I think your problem is that you don't provide your TranslateService at the root level of component, so each has its own instance leading to your problem. If you provide it at root level and set the default language once in your app component, it should work just like you want it to.

SirDieter avatar Jun 07 '18 13:06 SirDieter

I'll add that it's a bad practice to add logic that's not directly related to the view in component classes. In this case, it's a one-time configuration of the service and should be either done with APP_INITIALIZER tokens, or in the AppModule constructor, e.g.:

@NgModule({
  ...
  imports: [
    ...
    TranslateModule.forRoot(({
      loader: {
        provide: TranslateLoader,
        useClass: MyLoader
      }
    }))
  ]
})
export class AppModule {
  constructor(translateService: TranslateService) {
    translateService.addLangs(['en', 'fr']);
    translateService.setDefaultLang('en');
  }
}

Until the feature of this issue is implemented, we can use the above solution. I also suggest to fix the docs to better fit Angular best practices.

MaxArt2501 avatar Apr 05 '19 16:04 MaxArt2501