UNPKG

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