ngx-translate is a popular library for internationalization (i18n) in Angular applications. It provides a simple and efficient way to translate text and content within an application into multiple languages.
Read the following article if you are using Angular version 17 and above.
Installation
npm i @ngx-translate/core --save
npm i @ngx-translate/http-loader --save
Basic configuration and usage
Update app.module.ts
Import HttpClientModule
and HttpClient
The HttpClientModule
provides the HttpClient
service, which is used to send HTTP requests and receive responses from a server.
import { HttpClientModule, HttpClient } from '@angular/common/http';
imports: [
HttpClientModule,
],
Create a HttpLoaderFactory
function
The HttpLoaderFactory
function is used to configure the translation loader. It’s used when you’re asynchronously loading translation files. The HttpLoaderFactory
function will be used to load translation files using HttpClient
.
function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
Import TranslateModule
The TranslateModule
provides the necessary infrastructure for translating strings in your Angular application. The TranslatePipe
is part of the TranslateModule
provided by ngx-translate. When you import TranslateModule
into the Angular application, it includes the TranslatePipe
among other features provided by the module.
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient],
},
}),
],
Insert TranslateService
into the providers
The TranslateService
is the main service for translating strings.
providers: [TranslateService],
Create translation files
Create JSON files with translations. Place these files in the assets/i18n directory of your Angular project.
en.json
{
"HELLO": "Hello",
"WELCOME": "Welcome, {{name}}!",
}
sk.json
{
"HELLO": "Ahoj",
"WELCOME": "Vitaj {{name}}!",
}
“WELCOME
” includes the Slovak translation “Vitaj {{name}}!”. The placeholder {{name}} will be replaced with the name used in the application.
Translate text directly in the template
The TranslatePipe
allows you to translate text directly in your templates using the translate pipe operator (|
). It’s one of the core features of ngx-translate and is commonly used to display translated strings in Angular templates.
*.component.html
<p>{{ "HELLO" | translate }}</p>
<h2>{{ "WELCOME" | translate : { name: userName } }}</h2>
“WELCOME
” is the translation key. | translate
is a pipe that instructs Angular to translate the content.{ name: userName }
is an object passed as an argument to the translation pipe. It specifies the value for the name
placeholder in the translated string. userName
is a variable holding the user’s name.
Update component file
Inject TranslateService
into the component’s constructor. This allows you to use the translation service’s methods and properties within your component or service.
*.component.ts
constructor(private translate: TranslateService) {
this.translate.setDefaultLang('en');
}
If you don’t use this.translate.setDefaultLang(‘en’); to set the default language in your application, ngx-translate will still work, but it won’t have a default language explicitly set. You can set the default language in the TranslateModule
object.
Full example
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import {
TranslateLoader,
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
TranslateModule.forRoot({
defaultLanguage: 'en', // Set the default language
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient],
},
}),
],
providers: [TranslateService],
bootstrap: [AppComponent],
})
export class AppModule {}
en.json
{
"HELLO": "Hello",
"WELCOME": "Welcome, {{name}}!",
"BUTTON": {
"SAVE": "Save",
"CANCEL": "Cancel",
"CONSOLE": "CONSOLE",
"EN": "EN",
"SK": "SK"
}
}
sk.json
{
"HELLO": "Ahoj",
"WELCOME": "Vitaj {{name}}!",
"BUTTON": {
"SAVE": "Uložiť",
"CANCEL": "Zrušiť",
"CONSOLE": "KONZOLA",
"EN": "EN",
"SK": "SK"
}
}
A typical structure of translation files
src/
├── app/
│ ├── components/
│ ├── services/
│ ├── ...
└── assets/
└── i18n/
├── en.json // English translations
├── fr.json // French translations
└── es.json // Spanish translations
app.component.html
<h1>{{ title }}</h1>
<p>{{ "HELLO" | translate }}</p>
<h2>{{ "WELCOME" | translate : { name: userName } }}</h2>
<hr />
<button (click)="switchLang('EN')">{{ "BUTTON.EN" | translate }}</button>
<button (click)="switchLang('SK')">{{ "BUTTON.SK" | translate }}</button>
<hr />
<button>{{ "BUTTON.SAVE" | translate }}</button>
<button>{{ "BUTTON.CANCEL" | translate }}</button>
<button (click)="dynamicConsoleTranslation()">
{{ "BUTTON.CONSOLE" | translate }}
</button>
app.component.ts
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
title = 'ngx-translate demo';
userName = 'Matej';
constructor(private translate: TranslateService) {
// this.translate.setDefaultLang('en');
}
dynamicConsoleTranslation() {
const user = 'Admin';
this.translate
.get('WELCOME', { name: user })
.subscribe((translation: string) => {
console.log(translation); // Output: 'Welcome, Admin!' or corresponding translation
});
}
switchLang(lang: string) {
this.translate.use(lang.toLowerCase());
}
}
ngx-translate features
getLangs()
Returns an array of currently available langs. getLangs()
returns only the languages that have been loaded. If you’re not seeing any languages returned, it implies that no languages have been loaded.
const langs = this.translate.getLangs();
get()
get(key: string|Array, interpolateParams?: Object): Observable
gets the translated value of a key (or an array of keys) or the key if the value was not found.
After setting the language, use the get
method to retrieve translations
this.translate.use('en').subscribe(() => {
this.translate
.get(['HELLO', 'WELCOME'], { name: user })
.subscribe((translations) => {
console.log('Translations:', translations);
// Access specific translation keys
const hello = translations['HELLO'];
const welcome = translations['WELCOME'];
console.log(`HELLO: ${hello}`);
console.log(`WELCOME: ${welcome}`);
});
});
set()
set(key: string, value: string, lang?: string)
sets the translated value of a key.
this.translate.set('WELCOME', 'N/A');
Pipes
You can use the built-in pipes uppercase and lowercase in order to guarantee that your dynamically generated translation keys are either all uppercase or all lowercase.
*.component.ts
buttonType = ‘save’;
*.component.html
<button>{{ 'button.' + buttonType | uppercase | translate }}</button>
Directives
Using the translate directive instead of pipes is another way to handle translations in Angular templates, especially when you need to pass parameters.
<div [translate]="'WELCOME'" [translateParams]="{ name: userName }"></div>