調べながら書いたので間違っていたらスミマセン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>