I am using @ngx-translate. What I did is, I declare the content that I want to translate in both language files, in my case es.json
, and en.json
.
es.json:
"CONTENTS": {
"CONT_1": "TEXTO_1",
"CONT_2": "TEXTO_1",
"CONT_3": "TEXTO_1",
"CONT_4": "TEXTO_1",
"CONT_5": "TEXTO_1",
"CONT_6": "TEXTO_1",
"CONT_7": "TEXTO_1",
"CONT_8": "TEXTO_1",
"CONT_9": "TEXTO_1",
"CONT_10": "TEXTO_1",
"CONT_11": "TEXTO_1"
}
en.json:
"CONTENTS": {
"CONT_1": "TEXT_1",
"CONT_2": "TEXT_1",
"CONT_3": "TEXT_1",
"CONT_4": "TEXT_1",
"CONT_5": "TEXT_1",
"CONT_6": "TEXT_1",
"CONT_7": "TEXT_1",
"CONT_8": "TEXT_1",
"CONT_9": "TEXT_1",
"CONT_10": "TEXT_1",
"CONT_11": "TEXT_1"
}
In the component that I want to translate, in my case the contents.component.ts
, I: i) declare an array of contents; ii) inject the translate Service; iii) set it; iv) loop a for in which you construct an object that looks like this,
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-contents',
templateUrl: './contents.component.html',
styleUrls: ['./contents.component.css']
})
export class ContentsComponent implements OnInit {
// i) Declare an array
public contents = [];
// inject the translateService
constructor(public translateService: TranslateService) {
// iii) set it
translateService.addLangs(['es', 'en']);
translateService.setDefaultLang('es');
const browserLang = translateService.getBrowserLang();
translateService.use(browserLang.match(/es|en/) ? browserLang : 'es');
// loop for build a content object and push to the array
for (let index = 1; index <= 11; index++) {
const contentObj = {
id: index,
content: 'CONTENTS.CONT_' + index.toString()
};
this.contents.push(contentObj);
}
}
ngOnInit() {
}
}
Finally, in my contents.component.html looks like this
<ul>
<li *ngFor= "let content of contents" >
{{ content.content | translate }}
</li>
</ul>
You can improve this code and make it better :) I Hope could be useful.