1. 程式人生 > >在 Angular 專案中新增 i18n 外掛 ngx-translate

在 Angular 專案中新增 i18n 外掛 ngx-translate

摘要:本文將介紹在 Angular4 專案中配置 ngx-translate i18n 國際化元件

npm 安裝 ngx-translate 模組

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

在 Angular 專案配置

app.module.ts

新增

import { TranslateLoader, TranslateModule} from '@ngx-translate/core';
import { TranslateHttpLoader } from
'@ngx-translate/http-loader'; imports: [ TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateHttpLoader), deps: [Http] } }) ]

結果如下:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core'
; import { HttpModule, Http } from '@angular/http'; import { TranslateLoader, TranslateModule} from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { AppComponent } from './app.component'; export function createTranslateHttpLoader(http: Http) { return new
TranslateHttpLoader(http, './assets/i18n/', '.json'); } @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateHttpLoader), deps: [Http] } }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

app.component.ts

新增

import { TranslateService } from "@ngx-translate/core";

  constructor(public translateService: TranslateService) {

  }

  ngOnInit() {
    // --- set i18n begin ---
    this.translateService.addLangs(["zh", "en"]);
    this.translateService.setDefaultLang("zh");
    const browserLang = this.translateService.getBrowserLang();
    this.translateService.use(browserLang.match(/zh|en/) ? browserLang : 'zh');
    // --- set i18n end ---
  }

結果如下:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  constructor(public translateService: TranslateService) {

  }

  ngOnInit() {
    // --- set i18n begin ---
    this.translateService.addLangs(["zh", "en"]);
    this.translateService.setDefaultLang("zh");
    const browserLang = this.translateService.getBrowserLang();
    this.translateService.use(browserLang.match(/zh|en/) ? browserLang : 'zh');
    // --- set i18n end ---
  }
}

新增多語言檔案

* src/app/assets/ * 下建立 * i18n * 資料夾,並在資料夾內建立 * en.json ** zh.json * 檔案
angular-i18n-folder

測試

app.component.html

新增程式碼:

<div>
  <span> test the i18n module: ngx-translate</span>
  <h1>{{ 'hello' | translate }}</h1>
</div>

在 en.json 和 zh.json 檔案中新增配置

* en.json *

{
  "hello": "the word is hello"
}

* zh.json *

{
  "hello": "你好"
}

測試結果

在中文下
angular-i18n-result-zh

在英文下
angular-i18n-result-en

示例程式碼

參考文章