LoginSignup
17
22

More than 5 years have passed since last update.

Angularの多言語対応

Last updated at Posted at 2017-08-02

調べながら書いたので間違っていたらスミマセンmm

Angularの多言語対応

概要

Angularの4系でやっています。
Angularの多言語対応については、こちらのドキュメントを参考にしました(・ω・)

簡単にいうと...message.ja.xlf, message.en.xlfなどの言語ファイルを作り、ここで管理していくみたいです。

message.ja.xlf
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
  <file source-language="en" datatype="plaintext" original="ng2.template">
    <body>
      <trans-unit id="hello" datatype="html">
        <source>Hello world</source>
       <target>わんこ</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.ts</context>
          <context context-type="linenumber">1</context>
        </context-group>
      </trans-unit>
    </body>
  </file>
</xliff>

具体的なやり方

① package.jsonにこれを書きます。

package.json
"scripts": {
  "i18n": "ng-xi18n"
}

② component.htmlには、こんな感じで書きます。

app.component.html
<h1 i18n="@@hello">
  Hello world
</h1>

③ 辞書ファイルを作ります。

これでappにlocalができて、そこに辞書ファイルができます。
他の言語が欲しい場合は、messages.ja.xlfの部分をmessages.en.xlfなどとして増やしていきます。

npm run i18n -- --i18nFormat=xlf  --outFile=src/locale/messages.ja.xlf

④ 辞書ファイルを編集する

targetというところに変換したい文字をいれます。

messages.ja.xlf
<trans-unit id="hello" datatype="html">
  <source>
    Hello world
  </source>
  <target>
    こんにちは世界
  </target>
  ...
</trans-unit>
...

⑤ 実行します(・ω・)

--locale ja --i18n-format xlf --i18n-file src/locale/messages.ja.xlfとつけると日本語環境で実行されます。

ng serve --aot --locale ja --i18n-format xlf --i18n-file src/locale/messages.ja.xlf

⑥ ビルドします

ng build --aot --output-path dist/ja --base-href ja --locale ja --i18n-format xlf --i18n-file src/locale/messages.ja.xlf

言語の切り替え方法

こちらの記事を参考にさせていただきました!

app.component.ts
import { Component, LOCALE_ID, Inject } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  languages = [
    { code: 'en', label: 'English'},
    { code: 'es', label: 'Español'},
    { code: 'fr', label: 'Français'}
  ];
  constructor(@Inject(LOCALE_ID) protected localeId: string) {}
}

<!-- app.component.html -->
<h1 i18n>Hello World!</h1>
<template ngFor let-lang [ngForOf]="languages">
  <span *ngIf="lang.code !== localeId">
    <a href="/{{lang.code}}/">{{lang.label}}</a> </span>
  <span *ngIf="lang.code === localeId">{{lang.label}} </span>
</template>
17
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
22