abdou_behind_the_code
abdou_behind_the_code

Reputation: 519

Translate words into the class component (.ts) with ngx-translate (Angular)

I want to translate the content of a table into my typescript class. The table's data are fetched from JSON file located into /assets.

Is there a way to achieve that? How I can mark translation into a typescript class? PS: Please do not suggest doing it into the HTML, since it is not the desired way.

Upvotes: 1

Views: 2740

Answers (2)

Bmis Kemgoum
Bmis Kemgoum

Reputation: 1

I struggled with this same problem, but here is the solution that worked for me.

//Ts file

translatedString: string = 'KEY_STORED_IN_TRANSLATION_FILE'
<!-- HTML file -->

<li> {{ translatedString | translate }} </li>

Upvotes: 0

Amer
Amer

Reputation: 6706

As mentioned in the ngx-translate docs, you can achieve that by injecting the TranslateService into your class constructor, then use one of the following methods:

constructor(private translate: TranslateService) {}

ngOnInit(): void {
  // Using `instant` function:
  const translatedValueUsingInstant = this.translate.instant(
    'KEY_STORED_IN_TRANSLATION_FILE'
  );

  // OR using `get` function:
  let translatedValueUsingGet: string;
  this.translate
    .get('KEY_STORED_IN_TRANSLATION_FILE')
    .subscribe((value) => (translatedValueUsingGet = value));
}

Upvotes: 5

Related Questions