ngx-translate和* ngFor [英] ngx-translate and *ngFor

查看:106
本文介绍了ngx-translate和* ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

<div *ngFor="let service of services">
    <span><img  [src]="service.imgPath" alt="{{ service.name }}"/></span>
    <h4>{{ service.name}}</h4>
    <p>{{ service.desc }}</p>
</div> 

如何翻译具有3个参数的每个服务

How can I do translation of each service that have 3 parameters

在常规情况下,我使用{{ 'something' | translate }},其中"something"是 放在.json文件中

In regular case I use {{ 'something' | translate }} , where "something" is placed in .json file

"something" : "translation"

那么如何在ngFor状态下使用它? 它从.json中读取了一个对象,但没有读取我需要的对象数组

So how can a use it in state of ngFor? It read me an object from .json, but not array of objects that what I need in my case

推荐答案

首先,您需要在app.component.ts中导入ngx-translate:

First of all you will need to import ngx-translate in app.component.ts:

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
....
export function HttpLoaderFactory(http: HttpClient) {
   return new TranslateHttpLoader(http);
}
...
imports: [
    ...
    TranslateModule.forRoot({
        loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
        }
    })
]
...

然后,您需要在资产下拥有两个文件,一个文件f.i en.json用于英语,另一个文件用于西班牙语,例如es.json包含两个对象.在en.json中:

Then you need to have under assets two files one f.i en.json for English and another one for Spanish for instance, es.json containing two objects. In en.json:

{
  "something":  "something translation in English"
}

在es.json中:

{
  "something": "something translation in Spanish"
}

然后,在您提到的代码所在的组件中:

Then, in your component where you have the code you mention:

import { TranslateService } from '@ngx-translate/core';
...
constructor(private translate: TranslateService) {
        translate.setDefaultLang('en');
}
....

在模板中:

<div *ngFor="let service of services">
   <span><img  [src]="service.imgPath" alt="{{ service.name }}"/></span>
   <h4>{{service.name | translate}}</h4>
   <p>{{service.desc}}</p>
</div> 

请注意,您的服务对象必须包含字符串形式的内容,以便进行翻译.

Note that your services object must contain something as string so it will be feasible to be translated.

这篇关于ngx-translate和* ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆