参考扬帆天下博客:http://www.cnblogs.com/yangfantianxia/p/7878823.html
在他的基础上把设置语言的部分写在app.component.ts里,这样就变成全局加载了,使用时候只需要在html页写上{{ 'Id' | translate }} 就完成了,用起来很爽!
app.component.ts
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 这个页主要实现切换语言
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>
效果图: