Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - ngx-translate - Checking if translate key exist with Angular

I use ngx-translate in my Angular application.

My HTML template:

<span [ngClass]="(role === 'ADMIN') ? 'badge badge-danger' : 'badge badge-success'">{{ 'ADMIN.USER.ROLES.' + role | translate }}</span>

My i18n json file:

"ADMIN": {
  "USER": {
    "ROLES": {
      "ADMIN": "Administrator",
      "FOO": "Auditor FOO",
      "DOO": "Auditor DOO",
      "ROO": "Auditor ROO",
      "unknown": "Unknown"
    }
  }
}

If my role is BIPBIP, I want use 'ADMIN.USER.ROLES.unknown' key.

I looking for a HTML template solution (NOT Javascript):

this._translateService.get("app.key").subscribe(res=>{
    if(...) {
        // message does not exist
    }
    else {
        // message exists
    }
}))
like image 356
Stéphane GRILLON Avatar asked Mar 05 '19 16:03

Stéphane GRILLON


People also ask

How do you translate parameters in NGX?

Create an entry in the translation file (assets/i18n/en. json). The string interpolation syntax {{ }} is used to indicate a named parameter.

How does Ngx-translate work?

NGX-Translate is an internationalization library for Angular. It lets you define translations for your content in different languages and switch between them easily. Check out the demo on StackBlitz. It gives you access to a service, a directive and a pipe to handle any dynamic or static content.


1 Answers

Since I found no way to safely check for the presence of a translation, the best thing I could do is to check for equality synchronously:

hasTranslation(key: string): boolean {
  const translation = this.translateService.instant(key);
  return translation !== key && translation !== '';
}

However, I filed an issue with ngx-translate, asking for an official check method.

So, for your template you could just test with hasTranslation(x) ? ... : ...

like image 58
hoeni Avatar answered Oct 18 '22 23:10

hoeni