Translate Angular >=4 with ngx-translate and multiple modules

Frederic Lopes
Aug 9, 2017 · 2 min read

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-translate library.

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/core repository which has a good documentation (this story is a simple app real example of the implementation).

Frederic Lopes

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade