angulartypescriptngx-translate

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.


Solution

  • 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));
    }