How to use ngx-translate inside component

旧巷老猫 提交于 2021-02-10 06:42:08

问题


I am using ngx-translate inside my website, only problem is that i know how to use it inside html template it is working great, but how can i call key of JSON inside component?

This is what i need i have

app.html

 <div>{{"home" | translate }}</div>

this is working ok, but inside component i have something like this

 this.Items = [
      { title: 'Home', component: BookAServicePage, icon: 'settings' }
    ];

How can i replace this HOME to be read form a json file?


回答1:


I was able to figure out a solution. One thing to note is I had to utilize the DoCheck lifecycle event so that component level labels would translate without a refresh.

Here's how I did it.

import { Component, DoCheck } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'app-some',
    templateUrl: './some.component.html',
    styleUrls: ['./some.component.css']
})
export class SomeComponent implements DoCheck {

  headers = [];

  constructor(public translate: TranslateService){
  }

  ngDoCheck() {
    this.translate.get(['HEADER.PRIORITY', 'HEADER.STATE', 'HEADER.DATE_CREATED'])
    .subscribe(translations => {
        this.setHeaders(translations);
      });
  }

  setHeaders(translations) {
    this.headers = [
        {
            title: translations['HEADER.PRIORITY'],
            active: true
        },{
            title: translations['HEADER.STATE'],
            active: false
        },{
            title: translations['HEADER.DATE_CREATED'],
            active: false
        }];
  }
}


来源:https://stackoverflow.com/questions/48740922/how-to-use-ngx-translate-inside-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!