angular i18n tutorial code example

Example 1: multilanguage site angular

//Install ngx-translate
$ npm install @ngx-translate/core @ngx-translate/http-loader rxjs --save

//In your app.module.ts:
// import ngx-translate and the http loader
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {HttpClient, HttpClientModule} from '@angular/common/http';

@NgModule({
  ...
  imports: [
        ...
        // ngx-translate and the loader module
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            }
        })
    ],
  ...
})
export class AppModule { }
// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http);
}

//In the app.component.ts
import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    constructor(private translate: TranslateService) {
        translate.setDefaultLang('en');
    }
  useLanguage(language: string) {
    this.translate.use(language);
	}
}

//create the JSON file for the English translation: assets/i18n/en.json.
{
    "demo": {
        "title": "Translation demo",
        "text": "This is a simple demonstration app for ngx-translate"
    }
}
//do the same with another language (for example german)

//In the app.component.html
<p [translate]="'demo.text'"></p>

<button (click)="useLanguage('en')">en</button>
<button (click)="useLanguage('de')">de</button>

Example 2: i18n angular

content_copy
      
      <span i18n>Updated: {minutes, plural,
  =0 {just now}
  =1 {one minute ago}
  other {{{minutes}} minutes ago by {gender, select, male {male} female {female} other {other}}}}
</span>

Example 3: multilanguage site angular

//Installing:
//Terminal
$ npm install --save-dev angular-translate
//Embed in the html doc
<script src="path/to/angular-translate.js"></script>
//In the component.ts
var app = angular.module('myApp', ['pascalprecht.translate']);

app.config(['$translateProvider', function ($translateProvider) {
  $translateProvider.translations('en', {
    'TITLE': 'Hello',
    'FOO': 'This is a paragraph'
  });
 
  $translateProvider.translations('de', {
    'TITLE': 'Hallo',
    'FOO': 'Dies ist ein Absatz'
  });
 
  $translateProvider.preferredLanguage('en');
}]);
//In the component.html
<h1>{{ 'TITLE' | translate }}</h1>
<p>{{ 'FOO' | translate }}</p>

Example 4: i18n angular

content_copy
      
      ng xi18n  --format=xlf
ng xi18n  --format=xlf2
ng xi18n  --format=xmb