Getting started with translation in Angular 5 with ngx-translate
Introduction
Ngx-translate is an internationalization (i18n) library for Angular.
Let’s see how it works in an Angular 5 project with Visual Studio code
Step 1
Download following packages:
Core package
npm install @ngx-translate/core@^9.1.1 -–save
It’s important not to use version 10 because it’s only compatible with Angular 6
If you still use the Angular 4 get the latest compatible version (7.2.2).
Http loader package
npm install @ngx-translate/http-loader --save
if you’re still on Angular <4.3, please use Http from @angular/http with http-loader@0.1.0
Step 2
Create a httpLoaderFactory that inherits from TranslateHttpLoader
import { HttpClient } from '@angular/common/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; export function httpLoaderFactory(httpClient: HttpClient): TranslateHttpLoader { return new TranslateHttpLoader(httpClient, './assets/i18n/', '.json'); }
Assets/i18n will contains json resource file for each language: [lang].json
Step 3
Create languages files:
Example:
{ "APP" : { "TITLE" : "ngx-translate demonstration", "BODY" : "It works very well!" } }
Step 4
Setup app.module.ts by importing required modules:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { AppComponent } from './app.component'; import { HttpClientModule, HttpClient } from '@angular/common/http'; import { httpLoaderFactory } from './services/httpLoaderFactory'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: httpLoaderFactory, deps: [HttpClient] } }), ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step 5
Set language to use like this in your component:
import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector:'app-root', templateUrl:'./app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title='app'; constructor(private_translate:TranslateService) { this._translate.setDefaultLang('en'); this._translate.use('en'); } }
SetDefaultLang is used to set a fallback language when a translation isn’t found in the current language. use the lang to use, if the lang isn’t available, it will use the current loader to get them.
Build then a method that can allow to switch to another language.
Step 6
Test your app!
Example:
Easy right ? 😉