ngx-translate Documentation

Andreas Löw, Oliver Combe
Last updated:
ngx-translate Documentation

This is a slightly enhanced version of the original documentation included in ngx-translate's github repo, written by Oliver Combe. Enhancements: Nicer formatting, table of contents on the right side, links in the API, some comments and remarks that might be useful...

Installation

First you need to install the npm module:

npm install @ngx-translate/core --save

Choose the version corresponding to your Angular version:

Angular@ngx-translate/core@ngx-translate/http-loaderTutorial
16+15.x+8.x+Tutorial
13 - 15 (ivy only)14.x+7.x+Tutorial
10 - 1213.x+6.x+Tutorial
912.x+5.x+Tutorial
812.x+4.x+Tutorial
711.x+4.x+Tutorial
610.x3.xTutorial
58.x to 9.x1.x to 2.x
4.37.x or less1.x to 2.x
2 to 4.2.x7.x or less0.x

Usage

Importing the TranslateModule

To use ngx-translate in your project, import TranslateModule.forRoot() in the root NgModule of your application.

The forRoot() static method provides and configures services simultaneously. Ensure it's only called within the root module of your application, commonly referred to as AppModule.

This method lets you configure the TranslateModule by specifying a loader, a parser, and/or a missing translations handler. Additionally, you can set the default language using defaultLanguage.

See the section Translate Module API for details.

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {TranslateModule} from '@ngx-translate/core';

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule.forRoot({
            defaultLanguage: 'en'
        })
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Usage with SharedModules

If you use a SharedModule that you import in multiple other feature modules, you can export the TranslateModule to make sure you don't have to import it in every module.

@NgModule({
    exports: [
        CommonModule,
        TranslateModule
    ]
})
export class SharedModule { }

Note: Never call a forRoot static method in the SharedModule. You might end up with different instances of the service in your injector tree. But you can use forChild if necessary.

Lazy loaded modules

When you lazy load a module, you should use the forChild static method to import the TranslateModule.

Since lazy loaded modules use a different injector from the rest of your application, you can configure them separately with a different loader/compiler/parser/missing translations handler.

To make a child module extend translations from parent modules use extend: true. This will cause the service to also use translations from its parent module.

You can also isolate the service by using isolate: true. In which case the service is a completely isolated instance (for translations, current lang, events, ...). Otherwise, by default, it will share its data with other instances of the service (but you can still use a different loader/compiler/parser/handler even if you don't isolate the service).

@NgModule({
    imports: [
        TranslateModule.forChild({
            loader: {provide: TranslateLoader, useClass: CustomLoader},
            compiler: {provide: TranslateCompiler, useClass: CustomCompiler},
            parser: {provide: TranslateParser, useClass: CustomParser},
            missingTranslationHandler: {provide: MissingTranslationHandler, useClass: CustomHandler},
            isolate: true
        })
    ]
})
export class LazyLoadedModule { }

Loading language files dynamically

By default, there is no loader available. You can add translations manually using setTranslation but it is better to use a loader. You can write your own loader, or import an existing one.

Ngx-translate comes with TranslateHttpLoader which loads translation files using HttpClient. To use it, you need to install the http-loader package from @ngx-translate:

npm install @ngx-translate/http-loader --save

Once you've decided which loader to use, you have to set up the TranslateModule to use it.

Here is how you would use the TranslateHttpLoader to load translations from "/assets/i18n/[lang].json". [lang] is the lang that you're using, for english it could be en.

You have to create the translate loader inside a factory method if you want to use AoT compilation or Ionic.

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {HttpClientModule, HttpClient} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {AppComponent} from './app';

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
    imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            },
            defaultLanguage: 'en'
        })
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Initialize the TranslateService for your application

import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Component({
    selector: 'app',
    template: `
        <div>{{ 'app.hello' | translate:param }}</div>
    `
})
export class AppComponent {
    param = {value: 'world'};

    constructor(translate: TranslateService) {
        translate.setDefaultLang('en');
        translate.use('en');
    }
}

setDefaultLang() sets the default language. The default language is used as a fall-back if no translation is found in the currently selected language. You can also do this at application startup using the TranslateModule.forRoot({defaultLanguage:'en'}).

use() sets the current language for the application. If the selected language is not yet loaded, the loader is invoked to retrieve the file.

Define the translations

Once you've imported the TranslateModule, you can put your translations in a JSON file that will be imported with the TranslateHttpLoader. The following translations should be stored in ./assets/i18n/en.json.

{
    "app.hello": "hello {{value}}"
}

You can also define your translations manually with setTranslation().

translate.setTranslation('en', {
    "app.hello": 'hello {{value}}'
});

You can also use nested JSON objects — this allows you to create more structured translation files and provide some more context for the translators.

{
    "app": {
        "hello": "hello {{value}}"
    }
}

You can then access the value by using the dot notation, in this case app.hello.

We highly recommend using BabelEdit to manage your translations. It allows you to edit all JSON files at once, keeping them consistent. Features like PreTranslate allow you a fast preview of your application in other languages.

Work with translations in your components

You can either use the TranslateService, the TranslatePipe or the TranslateDirective to get your translation values.

Using translations in a component

With the service, it looks like this:

translate.get('app.hello', {value: 'world'}).subscribe((res: string) => {
    console.log(res);
    //=> 'hello world'
});

You might ask yourself, why get() is using a subscription to receive the translation. This is because your language file might not be loaded when the get() function is called. The update is triggered when the loading is complete.

You can also use stream() which is similar to get() but also fires when the language is changed.

There is also instant() — a synchronous method that returns the translation value immediately. This only works if the translation file is already loaded — or the translations are set using setTranslation().

Using translations in templates (TranslatePipe, TranslateDirective)

This is how you do it with the pipe:

<div>{{ 'app.hello' | translate:param }}</div>

And in your component define param like this:

param = {value: 'world'};

You can construct the translation keys dynamically by using simple string concatenation inside the template:

<ul *ngFor="let language of languages">
  <li>{{ 'languages.' + language | translate }}</li>
</ul>

Where languages is an array member of your component:

languages = ['en', 'fr', 'de'];

You language file would look like this;

{
    'languages': {
        'en': 'English',
        'fr': 'French',
        'de': 'German'
    }
}

You can also use the output of the built-in pipes uppercase and lowercase in order to guarantee that your dynamically generated translation keys are either all uppercase or all lowercase. For example:

<p>{{ 'roles.' + role | lowercase | translate }}</p>
role = 'ADMIN';

will match the following translation:

{
  "roles": {
    "admin": "Administrator"
  }
}

A plugin called ngx-translate-extract can help you keeping your source code and translation files in sync: It extracts the translation IDs from your source code. This does of course not work with dynamically created IDs like the one above.

This is how you use the directive:

<div [translate]="'app.hello'" [translateParams]="{value: 'world'}"></div>

Or even simpler using the content of your element as a key:

<div translate [translateParams]="{value: 'world'}">HELLO</div>

I recommend not use the pipe instead of the directive because both variants of the directive have issues. The one without a value causes warnings in some IDEs, the first one does currently not properly work with the message compiler plugin.

Using HTML tags in your translations

You can easily use raw HTML tags within your translations.

{
    "app.hello": "Welcome to my Angular application!<br><strong>This is an amazing app which uses the latest technologies!</strong>"
}

To render them, simply use the innerHTML attribute with the pipe on any element.

<div [innerHTML]="'app.hello' | translate"></div>

[innerHTML] should be safe to use because it uses Angular's DomSanitizer to filter potentially harmful tags like <script> or <style>.

TranslateModule API

forRoot(config: TranslateModuleConfig)

Use this static method in your application's root module to provide the TranslateService.

forChild(config: TranslateModuleConfig)

Use this static method in your (non-root) modules to import the directive/pipe.

TranslateModuleConfig

All properties in this configuration object are optional. The configuration can be used for forRoot() and forChild().

NameTypeDescription
loaderProviderProvides a TranslateLoader to load translations.
compilerProviderProvides a TranslateCompiler to prepare translations after loading. The default implementation does nothing.
parserProviderProvides a TranslateParser that interpolates parametes in translations. The default implementation checks translations for simple placeholders - e.g. {{value}}.
missingTranslationHandlerProviderProvides a MissingTranslationHandler that is invoked if a translation is not found. The default implementation returns the translation key. Also see userDefaultLang flag.
isolatebooleanIsolate the service instance, only works for lazy loaded modules or components with the "providers" property
extendbooleanExtends translations for a given language instead of ignoring them
useDefaultLangbooleanDefault: true. Set the behaviour in case a translation ID is not found. If set to true, the text from the default language is displayed. If you set it to false, MissingTranslationHandler will be used instead of the default language string.
defaultLanguagestringThe default language that is set on startup and is used to provide translations in case a translation is not found in the current language. Also see userDefaultLang flag.

TranslateService API

Properties

  • currentLang: The lang currently used
  • defaultLang: The default (fall-back) language
  • currentLoader: An instance of the loader currently used (static loader by default)
  • onLangChange: Event emitter that fires when a language changes
  • onTranslationChange: Event emitter that fires when the translations change
  • onDefaultLangChange: Event emitter that fires when the default language changes

onLangChange (Event Emitter)

An EventEmitter to listen to lang change events. A LangChangeEvent is an object with the properties:

NameTypeDescription
langstringthe code of the activated language
translationsanyan object containing your translations

Example:

onLangChange.subscribe((event: LangChangeEvent) => {
    // do something
);

onTranslationChange (Event Emitter)

An EventEmitter to listen to translation change events.

A TranslationChangeEvent is an object with the properties:

NameTypeDescription
langstringthe code of the activated language
translationsanyan object containing your translations

Example:

onTranslationChange.subscribe((event: TranslationChangeEvent) => {
    // do something
);

onDefaultLangChange (Event Emitter)

An EventEmitter to listen to default lang change events. A DefaultLangChangeEvent is an object with the following properties:

NameTypeDescription
langstringthe code of the activated language
translationsanyan object containing your translations

Example:

onDefaultLangChange.subscribe((event: DefaultLangChangeEvent) => {
    // do something
);

setDefaultLang

setDefaultLang(lang: string)

Sets the default language to use as a fallback. A translation is used from the default language, if no translation is found in the current language.

Calling setDefaultLang uses the loader to retrieve the language and updates the list of available languages which can be retrieved using getLangs.

getDefaultLang

getDefaultLang(): string

Returns the default language.

use

use(lang: string): Observable<any>

Changes the currently active language. This invokes the current loader to retrieve the translations if the language is not yet loaded.

Calling use uses the loader to retrieve the language and updates the list of available languages which can be retrieved using getLangs.

getTranslation

getTranslation(lang: string): Observable<any>

Gets an object of translations for a given language with the current loader.

setTranslation

setTranslation(lang: string, translations: Object, shouldMerge: boolean = false)

Manually sets an object of translations for a given language, set shouldMerge to true if you want to append the translations instead of replacing them.

Using setTranslation updates the list of available languages which can be retrieved using getLangs.

addLangs

addLangs(langs: Array<string>)

Add new languages to the list. This does not invoke the loader to retrieve the languages.

getLangs

getLangs(): string

Returns an array of currently available languages. The list can be extended calling setDefaultLang, use, setTranslation oraddLangs.

get

get(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object>

Gets the translated value of a key (or an array of keys) or the key if the value was not found. The Observable fires after the language file is loaded. Use stream if you want to get updates to language changes, too.

getStreamOnTranslationChange

getStreamOnTranslationChange(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object>

Returns a stream of translated values of a key (or an array of keys) or the key if the value was not found. Without any onTranslationChange`` events this returns the same value as get but it will also emit new values whenever the translation changes.

stream

stream(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object>

Returns a stream of translated values of a key (or an array of keys) or the key if the value was not found. Without any onLangChange events this returns the same value as get but it will also emit new values whenever the used language changes.

instant

instant(key: string|Array<string>, interpolateParams?: Object): string|Object

Gets the instant translated value of a key (or an array of keys).

This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead.

set

set(key: string, value: string, lang?: string)

Sets the translated value of a key.

reloadLang

reloadLang(lang: string): Observable<string|Object>

Calls resetLang and retrieves the translations object for the current loader

resetLang

resetLang(lang: string)

Removes the current translations for this lang.

You will have to call use, reloadLang or getTranslation again to be able to get translations

getBrowserLang

getBrowserLang(): string | undefined

Returns the current browser lang if available, or undefined otherwise.

getBrowserCultureLang

getBrowserCultureLang(): string | undefined

Returns the current browser culture language name (e.g. "de-DE" if available), or undefined otherwise

TranslateParser API

The TranslateParser service has 2 methods which might sometimes be useful:

interpolate

interpolate(expr: string | Function, params?: any): string

Interpolates a string to replace parameters or calls the interpolation function with the parameters.

Example:

parser.interpolate('This is a {{key}}!', {key: 'banana'})

Returns This is a banana!

Example:

parser.interpolate((params) => `This is a ${params.key}`, {key: 'banana'})

Returns This is a banana!

getValue

getValue(target: any, key: string): any

Gets a value from an object by composed key. The . is interpreted as sub-object:

Example:

parser.getValue({ key1: { keyA: 'value' }}, 'key1.keyA')

Returns value.

Write & use your own loader

If you want to write your own loader, you need to create a class that implements TranslateLoader. The only required method is getTranslation that must return an Observable. If your loader is synchronous, just use Observable.of to create an observable from your static value.

Example

class CustomLoader implements TranslateLoader {
    getTranslation(lang: string): Observable<any> {
        return Observable.of({KEY: 'value'});
    }
}

Once you've defined your loader, you can provide it in your configuration by adding it to its providers property.

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule.forRoot({
            loader: {provide: TranslateLoader, useClass: CustomLoader}
        })
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

How to use a compiler to preprocess translation values

By default, translation values are added "as-is". You can configure a compiler that implements TranslateCompiler to pre-process translation values when they are added (either manually or by a loader). A compiler has the following methods:

  • compile(value: string, lang: string): string | Function: Compiles a string to a function or another string.
  • compileTranslations(translations: any, lang: string): any: Compiles a (possibly nested) object of translation values to a structurally identical object of compiled translation values.

Using a compiler opens the door for powerful pre-processing of translation values. As long as the compiler outputs a compatible interpolation string or an interpolation function, arbitrary input syntax can be supported.

How to handle missing translations

You can setup a provider for the MissingTranslationHandler in the bootstrap of your application (recommended), or in the providers property of a component. It will be called when the requested translation is not available. The only required method is handle where you can do whatever you want. If this method returns a value or an observable (that should return a string), then this will be used. Just don't forget that it will be called synchronously from the instant method.

You can use useDefaultLang to decide whether default language string should be used when there is a missing translation in current language. Default value is true. If you set it to false, MissingTranslationHandler will be used instead of the default language string.

Example:

Create a Missing Translation Handler

import {MissingTranslationHandler, MissingTranslationHandlerParams} from '@ngx-translate/core';

export class MyMissingTranslationHandler implements MissingTranslationHandler {
    handle(params: MissingTranslationHandlerParams) {
        return 'some value';
    }
}

Setup the Missing Translation Handler in your module import by adding it to the forRoot (or forChild) configuration.

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule.forRoot({
            missingTranslationHandler: {provide: MissingTranslationHandler, useClass: MyMissingTranslationHandler},
            useDefaultLang: false
        })
    ],
    providers: [

    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

FAQ

I want to hot reload the translations in my application but reloadLang does not work

If you want to reload the translations and see the update on all your components without reloading the page, you have to load the translations manually and call setTranslation function which triggers onTranslationChange.

Plugins

  • Localize Router by @meeroslav: An implementation of routes localization for Angular. If you need localized urls (for example /fr/page and /en/page).
  • browser.i18n Loader by @pearnaly: loader for native translation files of browser extensions.
  • ngx-translate-extract by @biesbjerg: Extract translatable strings from your projects
  • MessageFormat Compiler by @lephyrus: Compiler for ngx-translate that uses messageformat.js to compile translations using ICU syntax for handling pluralization, gender, and more
  • ngx-translate-multi-http-loader by @denniske: Fetch multiple translation files with ngx-translate.
  • ngx-translate-cache by @jgpacheco: Simplified version of localize-router. If you are already using localize-router you don't need this extension. This extension is aimed only to facilitate language caching.
  • ngx-translate-module-loader by @larscom: Fetch multiple translation files (http) with ngx-translate. Each translation file gets it's own namespace out of the box and the configuration is very flexible.
  • ngx-translate-lint by @svoboda-rabstvo: Simple CLI tools for check ngx-translate keys in whole app
  • ngx-translate-cut by @bartholomej: Simple and useful pipe for cutting translations ✂️

Editors

  • BabelEdit — translation editor for JSON files

Additional Framework Support