如何通过ngx-translate的translate管道传递已翻译字符串数组给子组件
解决方法
你之前的写法会把翻译后的文本拼接成字符串而非数组传递给子组件,比如翻译后得到“是”和“否”,最终子组件收到的是"[是,否]"这个字符串,而非预期的数组['是','否'],所以无法正常解析。
下面提供两种无需在子组件中使用translate管道的解决方案:
方案一:在父组件代码中预生成翻译数组
通过TranslateService提前获取翻译结果,生成数组后传递给子组件:
- 在父组件的.ts文件中注入
TranslateService并处理翻译:
import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'parent-component', templateUrl: './parent.component.html' }) export class ParentComponent { translatedList: string[] = []; constructor(private translate: TranslateService) { // 批量获取指定key的翻译结果 this.translate.get(['yes', 'no']).subscribe(translations => { this.translatedList = [translations['yes'], translations['no']]; }); } }
- 在父组件模板中直接绑定数组:
<child-component [list]="translatedList"></child-component>
方案二:在模板中结合async管道处理
利用translate管道结合async管道,在模板中直接生成翻译后的数组:
<ng-container *ngIf="(['yes', 'no'] | translate) | async as translations"> <child-component [list]="[translations.yes, translations.no]"></child-component> </ng-container>
这里(['yes', 'no'] | translate)会返回一个Observable,通过async管道订阅并获取翻译结果对象,再从中提取值组成数组传递给子组件。
内容的提问来源于stack exchange,提问作者paulotarcio
相关产品推荐
相关产品推荐

