10

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
    }
}))
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154

3 Answers3

17

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) ? ... : ...

Max Amorim
  • 147
  • 1
  • 13
hoeni
  • 3,031
  • 30
  • 45
0

I really think this should be done with a function in JavaScript. Assuming you have an object with this mapping called ADMIN, you can do it like this.

<span [ngClass]="(role === 'ADMIN') ? 'badge badge-danger' : 'badge badge-success'">{{ this.ADMIN.USER.ROLES[role] ? 'ADMIN.USER.ROLES.' + role : 'ADMIN.USER.ROLES.unknown' | translate }}</span>
Jon
  • 2,456
  • 21
  • 28
  • @sgrillon You have to create that as a variable in the component that the HTML template is being used by. It should use the object from i18n.json. – Jon Mar 05 '19 at 20:18
  • this.ADMIN do not exist – Stéphane GRILLON Mar 05 '19 at 20:28
  • @sgrillon I understand that. I am telling you to create something with that information from `i18n.json`. So you need to create ADMIN or whatever you want to call it in your component. There is absolutely no way this will work without getting that information. – Jon Mar 05 '19 at 21:01
  • you use ngx-translate? – Stéphane GRILLON Mar 05 '19 at 21:13
  • No I don't actually. I was just telling you how I would go about it with what you provided. You can very easily create a loader (https://github.com/ngx-translate/core#write--use-your-own-loader), but you created the constraint of a HTML only solution. Do with my answer what you will. – Jon Mar 05 '19 at 21:24
0

In ngx-translate if translation does not exist the string of the key will be retured directly, so try this :

{{ ('EQUIPMENT-TYPE' + equipment.type.name | translate) !== 'EQUIPMENT-TYPE' + equipment.type.name  ?  ('EQUIPMENT-TYPE' + equipment.type.name | translate) : equipment.type.name }}

Thanks to https://www.nuomiphp.com/eplan/en/390812.html

panwar
  • 973
  • 9
  • 13