如何在Angular的i18n多语言字符串内插入动态变量并在HTML中渲染
Angular i18n 动态变量注入实现方案
方案一:使用主流第三方库 ngx-translate 实现(最常用)
步骤1:修正多语言JSON配置
首先调整JSON的占位符格式,同时修正原有JSON的语法错误:
{ "title": "Connection", "targets": { "facebook": "Facebook", "instagram": "Instagram", "linkedin": "LinkedIn" }, "message-success": "You connected successfully!", "message-failure": "Your connection failed", "failure-title": "Why did the connection to {{target}} failed?" }
其中{{target}}就是ngx-translate默认识别的变量占位符。
步骤2:HTML模板中传参渲染
直接在translate管道后传入变量对象即可,同时修正你原有HTML的语法错误:
<div [hidden]="!error"> <p-text [ngClass]="'-background-grey-4 spacing padded'"> {{ 'failure-title' | translate: {target: currentTarget} }} </p-text> </div>
这里的currentTarget是你组件TS中定义的变量,比如你要显示Facebook的错误提示,只需要在TS中给currentTarget赋值为'Facebook'即可。
如果你需要传入targets中对应语言的配置值
可以先取出对应target的多语言值再传入:
// 组件TS代码 import { TranslateService } from '@ngx-translate/core'; export class YourComponent { selectedTarget = 'facebook'; // 动态赋值的当前目标平台 currentTarget: string; constructor(private translate: TranslateService) { // 取出对应平台的多语言值 this.currentTarget = this.translate.instant(`targets.${this.selectedTarget}`); } }
方案二:使用Angular官方i18n实现
如果用的是Angular官方自带的i18n能力,按以下方式调整:
步骤1:修改JSON占位符
将占位符调整为官方标准格式{$变量名}:
"failure-title": "Why did the connection to {$target} failed?"
步骤2:模板中传参
<div [hidden]="!error"> <p-text [ngClass]="'-background-grey-4 spacing padded'" i18n> Why did the connection to {{currentTarget}} failed? </p-text> </div>
也可以在TS中调用$localize直接生成翻译文案:
const failureTitle = $localize `:@@failure-title:Why did the connection to ${this.currentTarget} failed?`;
内容的提问来源于stack exchange,提问作者Rakid Naomi
相关产品推荐
相关产品推荐

