Reputation: 51
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.
Upvotes: 5
Views: 5979
Reputation: 3290
There are two ways you could handle that:
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.
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;
}
}
Upvotes: 6
Reputation: 151
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
}
})
Upvotes: 2