本文介绍angular项目中,如何做国际化显示。

angular version: 12.1.0

引入国际化相关依赖

在依赖管理文件package.json中引入国际化相关依赖:

配置模块信息

app.module.ts文件中配置如下信息:

另外注意导入配置:

初始化国际化信息

angular项目入口组件文件app.component.ts文件中做初始化:

1
2
3
4
5
6
7
8
9
10
constructor(private translate: TranslateService) {

// 国际化
translate.addLangs(['en', 'zh-CN', 'zh-CNT']);
translate.setDefaultLang('zh-CN');
// 默认设置跟随浏览器语言
const browserLang = translate.getBrowserLang();
// 按文件名匹配使用的国际化配置文件
translate.use(browserLang.match(/en|zh-CN|zh-CNT/) ? browserLang : 'zh-CN');
}

添加国际化配置文件

最后,别忘记了要添加国际化配置文件哦:

配置文件内容比如如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
"title": "IT eBooks",
"translate": "Language",
"home": "All IT eBooks",
"categories": "Categories",
"language": {
"en": "English",
"zh": "Chinese",
"zht": "Chinese(Traditional)"
},
"search": "search",
"book-details":{
"desc": "Book Description",
"comment": "Comment",
"comment-form": {
"comment-control": {
"nzErrorTip": "Please write something here!",
"placeholder": "write any thing"
},
"name-control": {
"nzErrorTip": "Please write write your name",
"placeholder": "write your name"
},
"email-control": {
"nzErrorTip": "The input is not valid E-mail!",
"required": "Please input your E-mail!",
"placeholder": "email"
}
},
"related": "Related eBooks"
},
"download": "Download",
"submit": "submit",
"footer-text": "Reproduction of site books is authorized only for informative purposes and strictly for personal, private use. © 2019 IT eBooks"
}

使用国际化

在代码中使用

1
2
3
4
5
6
7
this.translate.get("book-details.desc").subscribe(value => {
console.log(value);
});

this.translate.get("title").subscribe(value => {
console.log(value);
});

html页面中使用

首先,要在所在组件中引入国际化服务:

1
constructor(public translate: TranslateService) {}

页面中使用:

1
2
3
<div class="all-it-ebook">
<span>{{'home' | translate}}</span>
</div>

关键代码:

1
{{'home' | translate}}

另外:

1
2
3
<span *ngIf="translate.currentLang === 'en'">{{'language.en' | translate}}</span>
<span *ngIf="translate.currentLang === 'zh-CN'">{{'language.zh' | translate}}</span>
<span *ngIf="translate.currentLang === 'zh-CNT'">{{'language.zht' | translate}}</span>


完!!!!!!!!!!!!!!!