UNPKG

25 kBMarkdownView Raw
1# @ngx-translate/core ![Build Status](https://github.com/ngx-translate/core/actions/workflows/main/badge.svg) [![npm version](https://badge.fury.io/js/%40ngx-translate%2Fcore.svg)](https://badge.fury.io/js/%40ngx-translate%2Fcore)
2
3The internationalization (i18n) library for Angular.
4
5Simple example using ngx-translate: https://stackblitz.com/github/ngx-translate/example
6
7Get the complete changelog here: https://github.com/ngx-translate/core/releases
8
9## Table of Contents
10* [Installation](#installation)
11* [Usage](#usage)
12 * [Import the TranslateModule](#1-import-the-translatemodule)
13 * [SharedModule](#sharedmodule)
14 * [Lazy loaded modules](#lazy-loaded-modules)
15 * [Configuration](#configuration)
16 * [AoT](#aot)
17 * [Define the default language for the application](#2-define-the-default-language-for-the-application)
18 * [Init the TranslateService for your application](#3-init-the-translateservice-for-your-application)
19 * [Define the translations](#4-define-the-translations)
20 * [Use the service, the pipe or the directive](#5-use-the-service-the-pipe-or-the-directive)
21 * [Use HTML tags](#6-use-html-tags)
22* [API](#api)
23 * [TranslateService](#translateservice)
24 * [Properties](#properties)
25 * [Methods](#methods)
26 * [Write & use your own loader](#write--use-your-own-loader)
27 * [Example](#example)
28 * [How to use a compiler to preprocess translation values](#how-to-use-a-compiler-to-preprocess-translation-values)
29 * [How to handle missing translations](#how-to-handle-missing-translations)
30 * [Example](#example-1)
31 * [Parser](#parser)
32 * [Methods](#methods)
33* [FAQ](#faq)
34 * [I'm getting an error `npm ERR! peerinvalid Peer [...]`](#im-getting-an-error-npm-err-peerinvalid-peer-)
35* [Plugins](#plugins)
36* [Editors](#editors)
37* [Additional Framework Support](#additional-framework-support)
38
39
40## Installation
41
42First you need to install the npm module:
43
44```sh
45npm install @ngx-translate/core --save
46```
47
48Choose the version corresponding to your Angular version:
49
50 Angular | @ngx-translate/core | @ngx-translate/http-loader
51 ------------- |---------------------| --------------------------
52 16+ | 15.x+ | 8.x+
53 13+ (ivy only)| 14.x+ | 7.x+
54 10/11/12/13 | 13.x+ | 6.x+
55 9 | 12.x+ | 5.x+
56 8 | 12.x+ | 4.x+
57 7 | 11.x+ | 4.x+
58 6 | 10.x | 3.x
59 5 | 8.x to 9.x | 1.x to 2.x
60 4.3 | 7.x or less | 1.x to 2.x
61 2 to 4.2.x | 7.x or less | 0.x
62
63
64## Usage
65
66#### 1. Import the `TranslateModule`:
67
68Finally, you can use ngx-translate in your Angular project. You have to import `TranslateModule.forRoot()` in the root NgModule of your application.
69
70The [`forRoot`](https://angular.io/api/router/RouterModule#forroot) static method is a convention that provides and configures services at the same time.
71Make sure you only call this method in the root module of your application, most of the time called `AppModule`.
72This method allows you to configure the `TranslateModule` by specifying a loader, a parser and/or a missing translations handler.
73
74```ts
75import {BrowserModule} from '@angular/platform-browser';
76import {NgModule} from '@angular/core';
77import {TranslateModule} from '@ngx-translate/core';
78
79@NgModule({
80 imports: [
81 BrowserModule,
82 TranslateModule.forRoot()
83 ],
84 bootstrap: [AppComponent]
85})
86export class AppModule { }
87```
88
89##### SharedModule
90
91If you use a [`SharedModule`](https://angular.io/guide/sharing-ngmodules) that you import in multiple other feature modules,
92you can export the `TranslateModule` to make sure you don't have to import it in every module.
93
94```ts
95@NgModule({
96 exports: [
97 CommonModule,
98 TranslateModule
99 ]
100})
101export class SharedModule { }
102```
103
104> 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.
105
106##### Lazy loaded modules
107
108When you lazy load a module, you should use the `forChild` static method to import the `TranslateModule`.
109
110Since 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.
111
112To make a child module extend translations from parent modules use `extend: true`. This will cause the service to also
113use translations from its parent module.
114
115You can also isolate the service by using `isolate: true`. In which case the service is a completely isolated instance (for translations, current lang, events, ...).
116Otherwise, 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).
117
118```ts
119@NgModule({
120 imports: [
121 TranslateModule.forChild({
122 loader: {provide: TranslateLoader, useClass: CustomLoader},
123 compiler: {provide: TranslateCompiler, useClass: CustomCompiler},
124 parser: {provide: TranslateParser, useClass: CustomParser},
125 missingTranslationHandler: {provide: MissingTranslationHandler, useClass: CustomHandler},
126 isolate: true
127 })
128 ]
129})
130export class LazyLoadedModule { }
131```
132
133##### Configuration
134
135By default, there is no loader available. You can add translations manually using `setTranslation` but it is better to use a loader.
136You can write your own loader, or import an existing one.
137For example you can use the [`TranslateHttpLoader`](https://github.com/ngx-translate/http-loader) that will load translations from files using HttpClient.
138
139To use it, you need to install the http-loader package from @ngx-translate:
140
141```sh
142npm install @ngx-translate/http-loader --save
143```
144
145Once you've decided which loader to use, you have to setup the `TranslateModule` to use it.
146
147Here 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`):
148
149```ts
150import {NgModule} from '@angular/core';
151import {BrowserModule} from '@angular/platform-browser';
152import {HttpClientModule, HttpClient} from '@angular/common/http';
153import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
154import {TranslateHttpLoader} from '@ngx-translate/http-loader';
155import {AppComponent} from './app';
156
157// AoT requires an exported function for factories
158export function HttpLoaderFactory(http: HttpClient) {
159 return new TranslateHttpLoader(http);
160}
161
162@NgModule({
163 imports: [
164 BrowserModule,
165 HttpClientModule,
166 TranslateModule.forRoot({
167 loader: {
168 provide: TranslateLoader,
169 useFactory: HttpLoaderFactory,
170 deps: [HttpClient]
171 }
172 })
173 ],
174 bootstrap: [AppComponent]
175})
176export class AppModule { }
177```
178
179##### AoT
180
181If 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.
182
183```ts
184export function createTranslateLoader(http: HttpClient) {
185 return new TranslateHttpLoader(http, './assets/i18n/', '.json');
186}
187
188@NgModule({
189 imports: [
190 BrowserModule,
191 HttpClientModule,
192 TranslateModule.forRoot({
193 loader: {
194 provide: TranslateLoader,
195 useFactory: (createTranslateLoader),
196 deps: [HttpClient]
197 }
198 })
199 ],
200 bootstrap: [AppComponent]
201})
202export class AppModule { }
203```
204
205#### 2. Define the `default language` for the application
206
207```ts
208@NgModule({
209 imports: [
210 BrowserModule,
211 TranslateModule.forRoot({
212 defaultLanguage: 'en'
213 })
214 ],
215 providers: [
216
217 ],
218 bootstrap: [AppComponent]
219})
220export class AppModule { }
221```
222
223#### 3. Init the `TranslateService` for your application:
224
225```ts
226import {Component} from '@angular/core';
227import {TranslateService} from '@ngx-translate/core';
228
229@Component({
230 selector: 'app',
231 template: `
232 <div>{{ 'HELLO' | translate:param }}</div>
233 `
234})
235export class AppComponent {
236 param = {value: 'world'};
237
238 constructor(translate: TranslateService) {
239 // this language will be used as a fallback when a translation isn't found in the current language
240 translate.setDefaultLang('en');
241
242 // the lang to use, if the lang isn't available, it will use the current loader to get them
243 translate.use('en');
244 }
245}
246```
247
248#### 4. Define the translations:
249
250Once 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`.
251
252```json
253{
254 "HELLO": "hello {{value}}"
255}
256```
257
258You can also define your translations manually with `setTranslation`.
259
260```ts
261translate.setTranslation('en', {
262 HELLO: 'hello {{value}}'
263});
264```
265
266The `TranslateParser` understands nested JSON objects. This means that you can have a translation that looks like this:
267
268```json
269{
270 "HOME": {
271 "HELLO": "hello {{value}}"
272 }
273}
274```
275
276You can then access the value by using the dot notation, in this case `HOME.HELLO`.
277
278#### 5. Use the service, the pipe or the directive:
279
280You can either use the `TranslateService`, the `TranslatePipe` or the `TranslateDirective` to get your translation values.
281
282With the **service**, it looks like this:
283
284```ts
285translate.get('HELLO', {value: 'world'}).subscribe((res: string) => {
286 console.log(res);
287 //=> 'hello world'
288});
289```
290
291This is how you do it with the **pipe**:
292
293```html
294<div>{{ 'HELLO' | translate:param }}</div>
295```
296
297And in your component define `param` like this:
298```ts
299param = {value: 'world'};
300```
301
302You can construct the translation keys dynamically by using simple string concatenation inside the template:
303
304```html
305<ul *ngFor="let language of languages">
306 <li>{{ 'LANGUAGES.' + language | translate }}</li>
307</ul>
308```
309
310Where `languages` is an array member of your component:
311
312```ts
313languages = ['EN', 'FR', 'BG'];
314```
315
316You 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:
317
318```html
319<p>{{ 'ROLES.' + role | uppercase | translate }}</p>
320```
321
322```ts
323role = 'admin';
324```
325
326will match the following translation:
327```json
328{
329 "ROLES": {
330 "ADMIN": "Administrator"
331 }
332}
333```
334
335This is how you use the **directive**:
336```html
337<div [translate]="'HELLO'" [translateParams]="{value: 'world'}"></div>
338```
339
340Or even simpler using the content of your element as a key:
341```html
342<div translate [translateParams]="{value: 'world'}">HELLO</div>
343```
344
345#### 6. Use HTML tags:
346
347You can easily use raw HTML tags within your translations.
348
349```json
350{
351 "HELLO": "Welcome to my Angular application!<br><strong>This is an amazing app which uses the latest technologies!</strong>"
352}
353```
354
355To render them, simply use the `innerHTML` attribute with the pipe on any element.
356
357```html
358<div [innerHTML]="'HELLO' | translate"></div>
359```
360
361## API
362
363### TranslateService
364
365#### Properties:
366
367- `currentLang`: The lang currently used
368- `currentLoader`: An instance of the loader currently used (static loader by default)
369- `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).
370
371 example:
372 ```ts
373 onLangChange.subscribe((event: LangChangeEvent) => {
374 // do something
375 });
376 ```
377- `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).
378
379 example:
380 ```ts
381 onTranslationChange.subscribe((event: TranslationChangeEvent) => {
382 // do something
383 });
384 ```
385- `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).
386
387 example:
388 ```ts
389 onDefaultLangChange.subscribe((event: DefaultLangChangeEvent) => {
390 // do something
391 });
392 ```
393
394#### Methods:
395
396- `setDefaultLang(lang: string)`: Sets the default language to use as a fallback
397- `getDefaultLang(): string`: Gets the default language
398- `use(lang: string): Observable<any>`: Changes the lang currently used
399- `getTranslation(lang: string): Observable<any>`: Gets an object of translations for a given language with the current loader
400- `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
401- `addLangs(langs: Array<string>)`: Add new langs to the list
402- `getLangs()`: Returns an array of currently available langs
403- `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
404- `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.
405- `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.
406- `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.
407- `set(key: string, value: string, lang?: string)`: Sets the translated value of a key
408- `reloadLang(lang: string): Observable<string|Object>`: Calls resetLang and retrieves the translations object for the current loader
409- `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
410- `getBrowserLang(): string | undefined`: Returns the current browser lang if available, or undefined otherwise
411- `getBrowserCultureLang(): string | undefined`: Returns the current browser culture language name (e.g. "de-DE" if available, or undefined otherwise
412
413#### Write & use your own loader
414
415If 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.
416
417##### Example
418
419```ts
420class CustomLoader implements TranslateLoader {
421 getTranslation(lang: string): Observable<any> {
422 return Observable.of({KEY: 'value'});
423 }
424}
425```
426
427Once you've defined your loader, you can provide it in your configuration by adding it to its `providers` property.
428
429```ts
430@NgModule({
431 imports: [
432 BrowserModule,
433 TranslateModule.forRoot({
434 loader: {provide: TranslateLoader, useClass: CustomLoader}
435 })
436 ],
437 bootstrap: [AppComponent]
438})
439export class AppModule { }
440```
441[Another custom loader example with translations stored in Firebase](FIREBASE_EXAMPLE.md)
442
443#### How to use a compiler to preprocess translation values
444
445By 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:
446
447- `compile(value: string, lang: string): string | Function`: Compiles a string to a function or another string.
448- `compileTranslations(translations: any, lang: string): any`: Compiles a (possibly nested) object of translation values to a structurally identical object of compiled translation values.
449
450Using 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.
451
452
453#### How to handle missing translations
454
455You 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.
456
457You 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.
458
459##### Example:
460
461Create a Missing Translation Handler
462
463```ts
464import {MissingTranslationHandler, MissingTranslationHandlerParams} from '@ngx-translate/core';
465
466export class MyMissingTranslationHandler implements MissingTranslationHandler {
467 handle(params: MissingTranslationHandlerParams) {
468 return 'some value';
469 }
470}
471```
472
473Setup the Missing Translation Handler in your module import by adding it to the `forRoot` (or `forChild`) configuration.
474
475```ts
476@NgModule({
477 imports: [
478 BrowserModule,
479 TranslateModule.forRoot({
480 missingTranslationHandler: {provide: MissingTranslationHandler, useClass: MyMissingTranslationHandler},
481 useDefaultLang: false
482 })
483 ],
484 providers: [
485
486 ],
487 bootstrap: [AppComponent]
488})
489export class AppModule { }
490```
491
492### Parser
493
494If you need it for some reason, you can use the `TranslateParser` service.
495
496#### Methods:
497- `interpolate(expr: string | Function, params?: any): string`: Interpolates a string to replace parameters or calls the interpolation function with the parameters.
498
499 `This is a {{ key }}` ==> `This is a value` with `params = { key: "value" }`
500 `(params) => \`This is a ${params.key}\` ==> `This is a value` with `params = { key: "value" }`
501- `getValue(target: any, key: string): any`: Gets a value from an object by composed key
502 `parser.getValue({ key1: { keyA: 'valueI' }}, 'key1.keyA') ==> 'valueI'`
503
504## FAQ
505
506#### I'm getting an error `npm ERR! peerinvalid Peer [...]`
507
508If 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.
509
510If 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 !
511
512If 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.
513
514#### I want to hot reload the translations in my application but `reloadLang` does not work
515
516If 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`.
517
518## Plugins
519- [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).
520- [.po files Loader](https://github.com/biesbjerg/ngx-translate-po-http-loader) by @biesbjerg: Use .po translation files with ngx-translate
521- [browser.i18n Loader](https://github.com/pearnaly/ngx-translate-browser-i18n-loader) by @pearnaly: loader for native translation files of browser extensions.
522- [ngx-translate-extract](https://github.com/biesbjerg/ngx-translate-extract) by @biesbjerg: Extract translatable strings from your projects
523- [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
524- [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).
525- [ngx-translate-multi-http-loader](https://github.com/denniske/ngx-translate-multi-http-loader) by @denniske: Fetch multiple translation files with ngx-translate.
526- [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.
527- [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.
528- [ngx-translate-all](https://github.com/irustm/ngx-translate-all) by @irustm: Automate translations for Angular projects.
529- [ngx-translate-migrate](https://github.com/irustm/ngx-translate-migrate) by @irustm: Automate migrations from ngx-translate to Angular i18n.
530- [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
531- [ngx-translate-cut](https://github.com/bartholomej/ngx-translate-cut) by @bartholomej: Simple and useful pipe for cutting translations ✂️
532
533## Editors
534- [BabelEdit](https://www.codeandweb.com/babeledit) — translation editor for JSON files
535- [Translation Manager](https://translation-manager-86c3d.firebaseapp.com/) — Progressive web-app, translation editor for JSON files
536- [Crowdl.io](https://crowdl.io) — Free translation management and crowd-translations tool with support for JSON files
537- [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`
538- [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.
539
540### Extensions
541
542#### VScode
543- [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.
544- [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.
545
546
547
548## Additional Framework Support
549
550* [Use with NativeScript](https://github.com/NathanWalker/nativescript-ng2-translate/issues/5#issuecomment-257606661)