Miomir Dancevic
Miomir Dancevic

Reputation: 6852

How to use ngx-translate inside component

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?

Upvotes: 2

Views: 3112

Answers (1)

Proximo
Proximo

Reputation: 6531

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
        }];
  }
}

Upvotes: 4

Related Questions