Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if translate key exist with angular2

I'm using ngx-translate and I have a static file where I defined the keys and their meanings.But when I use translation like this {{"app.key" | translate}} if key does not exist it prints "app.key" on the screen but I want be able to check if it exist or not how can I do that? Thanks in advance.

like image 736
arsonistslullaby Avatar asked Oct 19 '17 07:10

arsonistslullaby


2 Answers

There are two ways you could handle that:

1st variant: Check presence of a specific translation manually:

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:

if (this.translateService.instant(myKey) === myKey) {
  // key is not present
}

However, I filed an issue with ngx-translate, requesting a check method.

2nd variant: Use a generic handler for missing translations:

When you just want to find out about missing translations in general, you could set up a missingTranslationHandler:

@NgModule({
  imports: [
    ...
    TranslateModule.forRoot({
      missingTranslationHandler: {
        provide: MissingTranslationHandler,
        useClass: MyMissingTranslationHandler,
      },
    }),
  ],
})
export class myModule {
  ...
}


class MyMissingTranslationHandler implements MissingTranslationHandler {
  handle(params: MissingTranslationHandlerParams): any {
    console.warn(`Missing translation: ${params.key}`);
    return '[MISSING]: ' + params.key;
  }
}
like image 153
hoeni Avatar answered Sep 28 '22 22:09

hoeni


You need to use the get function from the API and if it returns the key you are checking for and not a translation it means that there is no translation available.

this._translateService.get("app.key").subscribe(res=>{
    if(res === "app.key") {
        // message does not exist
    }
    else {
        // message exists
    }
})
like image 40
Julien Moreau Avatar answered Sep 28 '22 22:09

Julien Moreau