Let's delve into an example using the ng2-translate
plugin.
I have a main module called AppModule
, along with child modules named TopPanelModule
and PagesModule
.
The ng2-translate
is configured for the AppModule
.
@NgModule({
imports: [TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
deps: [Http]
})],
exports: []
})
export class AppModule {
constructor(translateService: TranslateService) {
}
}
In the AppComponent
, I set languages and define basic configuration for the TranslateModule
.
@Component(...)
export class AppComponent {
constructor(translateService: TranslateService) {
translateService.addLangs(["en", "fr"]);
translateService.setDefaultLang('fr');
const browserLang = 'fr';
translateService.use(browserLang.match(/en|fr/) ? browserLang : 'en');
}
}
However, when attempting to utilize the TranslateModule
in the components of children modules - TopPanelComponent
and PagesComponent
, it doesn't function properly. Errors like pipe not existing or translation missing occur.
To address this issue, I created a separate module called MyTranslateModule
, configured the TranslateModule
within it, and then utilized this module in both the PagesModule
and TopPanelModule
.
@NgModule({
imports: [TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
deps: [Http]
})],
exports: [TranslateModule]
})
export class MyTranslateModule {
constructor(translateService: TranslateService) {
translateService.addLangs(["en", "fr"]);
translateService.setDefaultLang('fr');
const browserLang = 'fr';
translateService.use(browserLang.match(/en|fr/) ? browserLang : 'en');
console.log('AdminTrModule: calling');
}
}
and
@NgModule({
imports: [MyTranslateModule]
})
export class PagesModule{
}
@NgModule({
imports: [MyTranslateModule]
})
export class TopPanelModule{
}
This was a crucial step. It now works as intended! Though, there might be a concern regarding the creation of two instances of the TranslateModule. In case I change the language in the TopComponent
by invoking translateService.use('en')
, it only affects the language in the TopPanelModule
, not the PagesModule
.