angular i18n 國際化 多語言

參考揚帆天下博客:http://www.cnblogs.com/yangfantianxia/p/7878823.htmlhtml

在他的基礎上把設置語言的部分寫在app.component.ts裏,這樣就變成全局加載了,使用時候只須要在html頁寫上{{ 'Id' | translate }} 就完成了,用起來很爽!app

 app.component.tsthis

 1 import { Component, OnInit } from '@angular/core';
 2 import { TranslateService } from "@ngx-translate/core";
 3 
 4 @Component({
 5     selector: 'my-app',
 6     templateUrl: 'app/app.component.html'
 7 })
 8 
 9 export class AppComponent implements OnInit {
10     title = 'Angular4.3';
11     constructor(private translateService: TranslateService) { }
12     ngOnInit(): void {
13         this.translateService.addLangs(["zh", "en"]);
14         this.translateService.setDefaultLang("en");
15     }
16 }

i18n.ts  這個頁主要實現切換語言spa

 1 import { Component, OnInit } from '@angular/core';
 2 import { TranslateService } from "@ngx-translate/core";
 3 
 4 @Component({
 5     templateUrl: 'app/i18n/i18n.component.html'
 6 })
 7 
 8 export class i18nComponent implements OnInit {
 9     title = 'i18n';
10     constructor(private translateService: TranslateService) { }
11     ngOnInit(): void { }
12 }
 1 {{title}}
 2 <div>
 3     <button type="button" class="btn btn-outline-secondary" placement="right" ngbTooltip="English" (click)="this.translateService.use('en')">
 4         English
 5     </button>
 6     <button type="button" class="btn btn-outline-secondary" placement="right" ngbTooltip="中文" (click)="this.translateService.use('zh')">
 7         中文
 8     </button>
 9 </div>
10 <div>
11     {{ 'Id' | translate }}
12     {{ 'Name' | translate }}
13     {{ 'Age' | translate }}
14     {{ 'Gender' | translate }}
15     {{ 'Date of birth' | translate }}
16     {{ 'City' | translate }}
17 </div>

效果圖:code

相關文章
相關標籤/搜索