Angular i18n

ngx-translate

ngx-translate is an internationalization library for Angular.
Access translation file via httpmodule and translate.

Install for your package

npm install --save-dev @ngx-translate/core @ngx-translate/http-loader

Prepare language file

assets/i18n/ja.json

{
  "PAGE": {
    "HELLO": "こんにちは!",
    "HELLOWORLD": "こんにちは {{value}}"
  }
}

Module set

app.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
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.component';

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient);
}

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

Component Example

app.component.ts

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

@Component({
  selector: 'app-root',
  template: `
  <p>{{ "PAGE.HELLO" | translate }}</p><br/>
  <button (click)="log()">Alert</button><br/>
  <button (click)="log2()">Alert2</button><br/>
  `
})
export class AppComponent {
  constructor(public translate: TranslateService) {
    translate.setDefaultLang('ja');
  }

  log() {
    this.translate.get('PAGE.HELLO').subscribe((res: string) => {
      alert(res);
    });
  }

  log2() {
    this.translate.get('PAGE.HELLOWORLD', { value: '言葉' }).subscribe((res: string) => {
      alert(res);
    });
  }
}

This example use 2 types. One is template translation, the other is javascript base.
For template, we just use translate pipe.

{{ "PAGE.HELLO" | translate }}

For javascript, use TranslateService#get.