NGX-TRANSLATE:如何动态翻译字符串的数组

问题描述 投票:0回答:2
MON:Observable<string> = this.translate.get('CALENDAR.MON'); TUE:Observable<string> = this.translate.get('CALENDAR.TUE'); WED:Observable<string> = this.translate.get('CALENDAR.WED'); THU:Observable<string> = this.translate.get('CALENDAR.THU'); FRI:Observable<string> = this.translate.get('CALENDAR.FRI'); SAT:Observable<string> = this.translate.get('CALENDAR.SAT'); SUN:Observable<string> = this.translate.get('CALENDAR.SUN'); daysOfWeeks:string[] = [`${this.MON}`, `${this.TUE}`, `${this.WED}`, `${this.THU}`, `${this.FRI}`, `${this.SAT}`, `${this.SUN}`]; constructor( public translate: TranslateService ) { }

Html:

<div *ngFor="let day of daysOfWeeks">{{ day | async}}</div>
我还尝试将管道直接使用到NGFOR中,但仍然不起作用。
    

我将分享两种解决此问题的方法。
1-您可以使用
translateservice.instant

angular ngx-translate
2个回答
3
投票
启动(键:字符串|数组,interpalyparams?:对象): 字符串|对象:获取键的即时翻译值(或数组 钥匙)。 /!\此方法是同步的,默认文件加载程序 是异步的。您有责任知道您何时 翻译已经加载,可以安全使用此方法。如果 您不确定,然后应该使用GET方法。

就像这个

//for single const traslateSingle :string = this.translateService.instant("Monday"); // translated "Monday" //for list const transaletedList = ["Monday", "Tuesday", "Wednesday"].map(x=> this.translateService.instant(x)) // translated Week days 但是它有自己的问题 如果尚未加载翻译怎么办? 如果语言选择发生了变化,那么现在您有责任获得更新的翻译

2-在

component.html

中使用

translate

管道
const daysOfWeeks = ["Monday", "Tuesday", "Wednesday"]
 <div *ngFor="let day of daysOfWeeks">{{ day | translate}}</div>

履行责任并自动翻译文本和检测语言更改,然后再次翻译。

因此,这是您问题的更好解决方案。

Tl;dr

也有可能使用索引参考。认为您有2种不同的语言,例如英语和土耳其语;

en.json

{ ... "months": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] }

tr.json

1
投票

{ ... "months": ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"] }

通过翻译即时输出的那些数组定义:

getMonths(months: string[]): string[] { return months.map((_, i) => this.translateService.instant(`months.${i}`)); } 最终,它给出了新数组的结果,该数组通过调用该方法(getMonths

)将其翻译为每个项目

@for (item of ('common.arrayOf Something' | translate); track item) { <li class="title-18 normal">{{item}}</li> } 我像这个

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.