ngx-translate and *ngFor

2019-07-13 00:16发布

I have this code

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

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

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

"something" : "translation"

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

2条回答
闹够了就滚
2楼-- · 2019-07-13 00:52

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]
        }
    })
]
...

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"
}

In 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');
}
....

In the template:

<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.

查看更多
我只想做你的唯一
3楼-- · 2019-07-13 00:53
use translate.get('jsonKey').subscribe( (response: any)=> {

services = response;


});

Note - //make sure your json structure is correct

查看更多
登录 后发表回答