1//Install ngx-translate
2$ npm install @ngx-translate/core @ngx-translate/http-loader rxjs --save
3
4//In your app.module.ts:
5// import ngx-translate and the http loader
6import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
7import {TranslateHttpLoader} from '@ngx-translate/http-loader';
8import {HttpClient, HttpClientModule} from '@angular/common/http';
9
10@NgModule({
11 ...
12 imports: [
13 ...
14 // ngx-translate and the loader module
15 HttpClientModule,
16 TranslateModule.forRoot({
17 loader: {
18 provide: TranslateLoader,
19 useFactory: HttpLoaderFactory,
20 deps: [HttpClient]
21 }
22 })
23 ],
24 ...
25})
26export class AppModule { }
27// required for AOT compilation
28export function HttpLoaderFactory(http: HttpClient) {
29 return new TranslateHttpLoader(http);
30}
31
32//In the app.component.ts
33import {Component} from '@angular/core';
34import {TranslateService} from '@ngx-translate/core';
35
36@Component({
37 selector: 'app-root',
38 templateUrl: './app.component.html',
39 styleUrls: ['./app.component.scss']
40})
41export class AppComponent {
42 constructor(private translate: TranslateService) {
43 translate.setDefaultLang('en');
44 }
45 useLanguage(language: string) {
46 this.translate.use(language);
47 }
48}
49
50//create the JSON file for the English translation: assets/i18n/en.json.
51{
52 "demo": {
53 "title": "Translation demo",
54 "text": "This is a simple demonstration app for ngx-translate"
55 }
56}
57//do the same with another language (for example german)
58
59//In the app.component.html
60<p [translate]="'demo.text'"></p>
61
62<button (click)="useLanguage('en')">en</button>
63<button (click)="useLanguage('de')">de</button>
1//Installing:
2//Terminal
3$ npm install --save-dev angular-translate
4//Embed in the html doc
5<script src="path/to/angular-translate.js"></script>
6//In the component.ts
7var app = angular.module('myApp', ['pascalprecht.translate']);
8
9app.config(['$translateProvider', function ($translateProvider) {
10 $translateProvider.translations('en', {
11 'TITLE': 'Hello',
12 'FOO': 'This is a paragraph'
13 });
14
15 $translateProvider.translations('de', {
16 'TITLE': 'Hallo',
17 'FOO': 'Dies ist ein Absatz'
18 });
19
20 $translateProvider.preferredLanguage('en');
21}]);
22//In the component.html
23<h1>{{ 'TITLE' | translate }}</h1>
24<p>{{ 'FOO' | translate }}</p>