----------------------------------------
I wanted to do a short story to briefly explain to those who are not familiar with ngx-translate in Angular 4 applications, as I was few minutes ago and managed to fix my issue.
Most of the time you only need to use the app.module.ts for a small application but usually, apps grow and new modules appear by the way. I will go to the point in a multiple module implementation of the ngx-translatelibrary.
Your app.module.ts should import:
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
Then, you need export your loader function (insert your own path to your i18n assets):
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
Once those done, simply add in NgModules Imports:
imports: [
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient],
}
})
],
Once your app.module.ts configured with ngx-translate, let’s implement it into your other modules. For this, I strongly recommend to use a shared.module as mentioned in ngx-translate repository, then you don’t need to worry about importing TranslateModule everytime. You only need to add this in your shared.module:
import { NgModule } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
@NgModule({
exports: [
TranslateModule,
]
})
export class SharedModule { }
You are now ready! Just import your shared.module in your other modules:
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared.module';
import { AnotherComponent } from './home.component';
@NgModule({
declarations: [
AnotherComponent
],
imports: [
SharedModule
]
})
export class AnotherModule { }
and add the TranslateService in the constructor of your module components, just like this:
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-home',
templateUrl: './another.component.html',
})
export class AnotherComponent {
constructor(public translate: TranslateService) { }
}
Not a big deal nah? Strongly recommend to go through ngx-translate/corerepository which has a good documentation (this story is a simple app real example of the implementation).