Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

https://github.com/ngx-translate/core

The internationalization (i18n) library for Angular
https://github.com/ngx-translate/core

angular angular2 i18n ngx ngx-translate npm-package translation

Last synced: about 1 month ago
JSON representation

The internationalization (i18n) library for Angular

Lists

README

        

# @ngx-translate/core ![Build Status](https://github.com/ngx-translate/core/actions/workflows/main.yml/badge.svg) [![npm version](https://badge.fury.io/js/%40ngx-translate%2Fcore.svg)](https://badge.fury.io/js/%40ngx-translate%2Fcore)

The internationalization (i18n) library for Angular.

Simple example using ngx-translate: https://stackblitz.com/github/ngx-translate/example

Get the complete changelog here: https://github.com/ngx-translate/core/releases

## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [Import the TranslateModule](#1-import-the-translatemodule)
* [SharedModule](#sharedmodule)
* [Lazy loaded modules](#lazy-loaded-modules)
* [Configuration](#configuration)
* [AoT](#aot)
* [Define the default language for the application](#2-define-the-default-language-for-the-application)
* [Init the TranslateService for your application](#3-init-the-translateservice-for-your-application)
* [Define the translations](#4-define-the-translations)
* [Use the service, the pipe or the directive](#5-use-the-service-the-pipe-or-the-directive)
* [Use HTML tags](#6-use-html-tags)
* [API](#api)
* [TranslateService](#translateservice)
* [Properties](#properties)
* [Methods](#methods)
* [Write & use your own loader](#write--use-your-own-loader)
* [Example](#example)
* [How to use a compiler to preprocess translation values](#how-to-use-a-compiler-to-preprocess-translation-values)
* [How to handle missing translations](#how-to-handle-missing-translations)
* [Example](#example-1)
* [Parser](#parser)
* [Methods](#methods)
* [FAQ](#faq)
* [I'm getting an error `npm ERR! peerinvalid Peer [...]`](#im-getting-an-error-npm-err-peerinvalid-peer-)
* [Plugins](#plugins)
* [Editors](#editors)
* [Additional Framework Support](#additional-framework-support)

## Installation

First you need to install the npm module:

```sh
npm install @ngx-translate/core --save
```

Choose the version corresponding to your Angular version:

Angular | @ngx-translate/core | @ngx-translate/http-loader
------------- |---------------------| --------------------------
16+ | 15.x+ | 8.x+
13+ (ivy only)| 14.x+ | 7.x+
10/11/12/13 | 13.x+ | 6.x+
9 | 12.x+ | 5.x+
8 | 12.x+ | 4.x+
7 | 11.x+ | 4.x+
6 | 10.x | 3.x
5 | 8.x to 9.x | 1.x to 2.x
4.3 | 7.x or less | 1.x to 2.x
2 to 4.2.x | 7.x or less | 0.x

## Usage

#### 1. Import the `TranslateModule`:

Finally, you can use ngx-translate in your Angular project. You have to import `TranslateModule.forRoot()` in the root NgModule of your application.

The [`forRoot`](https://angular.io/api/router/RouterModule#forroot) static method is a convention that provides and configures services at the same time.
Make sure you only call this method in the root module of your application, most of the time called `AppModule`.
This method allows you to configure the `TranslateModule` by specifying a loader, a parser and/or a missing translations handler.

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

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

##### SharedModule

If you use a [`SharedModule`](https://angular.io/guide/sharing-ngmodules) 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.

```ts
@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).

```ts
@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 { }
```

##### Configuration

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.
For example you can use the [`TranslateHttpLoader`](https://github.com/ngx-translate/http-loader) that will load translations from files using HttpClient.

To use it, you need to install the http-loader package from @ngx-translate:

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

Once you've decided which loader to use, you have to setup 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`):

```ts
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';

// AoT requires an exported function for factories
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}

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

##### AoT

If you want to configure a custom `TranslateLoader` while using [AoT compilation](https://angular.io/docs/ts/latest/cookbook/aot-compiler.html) or [Ionic](http://ionic.io/), you must use an exported function instead of an inline function.

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

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

#### 2. Define the `default language` for the application

```ts
@NgModule({
imports: [
BrowserModule,
TranslateModule.forRoot({
defaultLanguage: 'en'
})
],
providers: [

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

#### 3. Init the `TranslateService` for your application:

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

@Component({
selector: 'app',
template: `

{{ 'HELLO' | translate:param }}

`
})
export class AppComponent {
param = {value: 'world'};

constructor(translate: TranslateService) {
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang('en');

// the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use('en');
}
}
```

#### 4. 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 `en.json`.

```json
{
"HELLO": "hello {{value}}"
}
```

You can also define your translations manually with `setTranslation`.

```ts
translate.setTranslation('en', {
HELLO: 'hello {{value}}'
});
```

The `TranslateParser` understands nested JSON objects. This means that you can have a translation that looks like this:

```json
{
"HOME": {
"HELLO": "hello {{value}}"
}
}
```

You can then access the value by using the dot notation, in this case `HOME.HELLO`.

#### 5. Use the service, the pipe or the directive:

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

With the **service**, it looks like this:

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

This is how you do it with the **pipe**:

```html

{{ 'HELLO' | translate:param }}

```

And in your component define `param` like this:
```ts
param = {value: 'world'};
```

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

```html


  • {{ 'LANGUAGES.' + language | translate }}


```

Where `languages` is an array member of your component:

```ts
languages = ['EN', 'FR', 'BG'];
```

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:

```html

{{ 'ROLES.' + role | uppercase | translate }}


```

```ts
role = 'admin';
```

will match the following translation:
```json
{
"ROLES": {
"ADMIN": "Administrator"
}
}
```

This is how you use the **directive**:
```html


```

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

HELLO

```

#### 6. Use HTML tags:

You can easily use raw HTML tags within your translations.

```json
{
"HELLO": "Welcome to my Angular application!
This is an amazing app which uses the latest technologies!"
}
```

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

```html


```

## API

### TranslateService

#### Properties:

- `currentLang`: The lang currently used
- `currentLoader`: An instance of the loader currently used (static loader by default)
- `onLangChange`: An EventEmitter to listen to lang change events. A `LangChangeEvent` is an object with the properties `lang: string` & `translations: any` (an object containing your translations).

example:
```ts
onLangChange.subscribe((event: LangChangeEvent) => {
// do something
});
```
- `onTranslationChange`: An EventEmitter to listen to translation change events. A `TranslationChangeEvent` is an object with the properties `lang: string` & `translations: any` (an object containing your translations).

example:
```ts
onTranslationChange.subscribe((event: TranslationChangeEvent) => {
// do something
});
```
- `onDefaultLangChange`: An EventEmitter to listen to default lang change events. A `DefaultLangChangeEvent` is an object with the properties `lang: string` & `translations: any` (an object containing your translations).

example:
```ts
onDefaultLangChange.subscribe((event: DefaultLangChangeEvent) => {
// do something
});
```

#### Methods:

- `setDefaultLang(lang: string)`: Sets the default language to use as a fallback
- `getDefaultLang(): string`: Gets the default language
- `use(lang: string): Observable`: Changes the lang currently used
- `getTranslation(lang: string): Observable`: Gets an object of translations for a given language with the current loader
- `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
- `addLangs(langs: Array)`: Add new langs to the list
- `getLangs()`: Returns an array of currently available langs
- `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
- `getStreamOnTranslationChange(key: string|Array, interpolateParams?: Object): Observable`: 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(key: string|Array, interpolateParams?: Object): Observable`: 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(key: string|Array, 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(key: string, value: string, lang?: string)`: Sets the translated value of a key
- `reloadLang(lang: string): Observable`: Calls resetLang and retrieves the translations object for the current loader
- `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(): string | undefined`: Returns the current browser lang if available, or undefined otherwise
- `getBrowserCultureLang(): string | undefined`: Returns the current browser culture language name (e.g. "de-DE" if available, or undefined otherwise

#### 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`](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/of.md) to create an observable from your static value.

##### Example

```ts
class CustomLoader implements TranslateLoader {
getTranslation(lang: string): Observable {
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.

```ts
@NgModule({
imports: [
BrowserModule,
TranslateModule.forRoot({
loader: {provide: TranslateLoader, useClass: CustomLoader}
})
],
bootstrap: [AppComponent]
})
export class AppModule { }
```
[Another custom loader example with translations stored in Firebase](FIREBASE_EXAMPLE.md)

#### 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

```ts
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.

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

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

### Parser

If you need it for some reason, you can use the `TranslateParser` service.

#### Methods:
- `interpolate(expr: string | Function, params?: any): string`: Interpolates a string to replace parameters or calls the interpolation function with the parameters.

`This is a {{ key }}` ==> `This is a value` with `params = { key: "value" }`
`(params) => \`This is a ${params.key}\` ==> `This is a value` with `params = { key: "value" }`
- `getValue(target: any, key: string): any`: Gets a value from an object by composed key
`parser.getValue({ key1: { keyA: 'valueI' }}, 'key1.keyA') ==> 'valueI'`

## FAQ

#### I'm getting an error `npm ERR! peerinvalid Peer [...]`

If you're using npm 2.x, upgrade to npm 3.x, because npm 2 doesn't handle peer dependencies well. With npm 2 you could only use fixed versions, but with npm 3 you can use `^` to use a newer version if available.

If you're already on npm 3, check if it's an error (`npm ERR!`) or a warning (`npm WARN!`), warning are just informative and if everything works then don't worry !

If you're using an old version of Angular and ngx-translate requires a newer version then you should consider upgrading your application to use the newer angular 2 version. There is always a reason when I upgrade the minimum dependencies of the library. Often it is because Angular had a breaking changes. If it's not an option for you, then check [the changelog](https://github.com/ngx-translate/core/releases) to know which version is the last compatible version for you.

#### 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](https://github.com/Greentube/localize-router) by @meeroslav: An implementation of routes localization for Angular. If you need localized urls (for example /fr/page and /en/page).
- [.po files Loader](https://github.com/biesbjerg/ngx-translate-po-http-loader) by @biesbjerg: Use .po translation files with ngx-translate
- [browser.i18n Loader](https://github.com/pearnaly/ngx-translate-browser-i18n-loader) by @pearnaly: loader for native translation files of browser extensions.
- [ngx-translate-extract](https://github.com/biesbjerg/ngx-translate-extract) by @biesbjerg: Extract translatable strings from your projects
- [MessageFormat Compiler](https://github.com/lephyrus/ngx-translate-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-zombies](https://marketplace.visualstudio.com/items?itemName=seveseves.ngx-translate-zombies) by @seveves: A vscode extension that finds unused translation keys and shows them in a diff view (so called zombies).
- [ngx-translate-multi-http-loader](https://github.com/denniske/ngx-translate-multi-http-loader) by @denniske: Fetch multiple translation files with ngx-translate.
- [ngx-translate-cache](https://github.com/jgpacheco/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](https://github.com/larscom/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-all](https://github.com/irustm/ngx-translate-all) by @irustm: Automate translations for Angular projects.
- [ngx-translate-migrate](https://github.com/irustm/ngx-translate-migrate) by @irustm: Automate migrations from ngx-translate to Angular i18n.
- [ngx-translate-lint](https://github.com/svoboda-rabstvo/ngx-translate-lint) by @svoboda-rabstvo: Simple CLI tools for check ngx-translate keys in whole app
- [ngx-translate-cut](https://github.com/bartholomej/ngx-translate-cut) by @bartholomej: Simple and useful pipe for cutting translations ✂️

## Editors
- [BabelEdit](https://www.codeandweb.com/babeledit) — translation editor for JSON files
- [Translation Manager](https://translation-manager-86c3d.firebaseapp.com/) — Progressive web-app, translation editor for JSON files
- [Crowdl.io](https://crowdl.io) — Free translation management and crowd-translations tool with support for JSON files
- [ngx-translate-editor](https://github.com/svoboda-rabstvo/ngx-translate-editor) - Simple GUI for CRUD translate files of `ngx-translate`, which included `ngx-translate-lint`
- [tl8.io](https://tl8.io) - A multi-platform application to enable the whole product team, including non-developers, to modify translations. WYSIWYG interface. Results can be downloaded as JSON and copied in the project as is.

### Extensions

#### VScode
- [Generate Translation](https://marketplace.visualstudio.com/items?itemName=thiagocordeirooo.generate-translation) by [@thiagocordeirooo](https://github.com/thiagocordeirooo): A visual studio code extension for you to generate the translations without leaving the current file.
- [Lingua](https://marketplace.visualstudio.com/items?itemName=chr33z.lingua-vscode&utm_source=www.vsixhub.com) by [@chr33z](https://github.com/chr33z): A visual studio code extension to help managing translations for ngx-translate - featuring inline translation lookup and in-place translation creation and editing.

## Additional Framework Support

* [Use with NativeScript](https://github.com/NathanWalker/nativescript-ng2-translate/issues/5#issuecomment-257606661)