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.
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;
}
}
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
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With