ngx-translate default text if key is missing or translation file is being loaded

非 Y 不嫁゛ 提交于 2020-04-14 07:46:42

问题


I'm setting up a new Angular 7 app. I want to set a default text for translation. So in the translation {{ 'wait' | translate }}, I want to set text 'Waiting Now' as default text if there are any fallback. Means if data is being loaded or key is missing then passed value (in this case Waiting Now) should appear.

I was trying to do something like {{ 'Intro' | translate:'localizedText' }}

Not didn't worked

{{ 'Intro' | translate:'localizedText' }}

I expect result should come as

{{ 'Intro' | translate:'localizedText' }} => Intro (If being loaded or missing key)

{{ 'Intro' | translate:'localizedText' }} => translated text


回答1:


you will need to use a custom MissingTranslationHandler Like so:

in your app.module or wherever you are loading TranslateModule.forRoot do this:

@Injectable()
export class MyMissingTranslationHandler implements MissingTranslationHandler {
    handle(params: MissingTranslationHandlerParams): string {
        return `**MISSING KEY: ${params.key}**`;
    }
}

And in your providers:[] add this: (After you import MissingTranslationHandler)

{
    provide: MissingTranslationHandler,
    useClass: MyMissingTranslationHandler
},

See this link for more details:

https://github.com/ngx-translate/core#how-to-handle-missing-translations

To return a default values for the missing you can try this:

1- Create an object/json to contain the default values, that json should contain the same structure as the original json.

const alternativeJson = {  
       value1: 'default1'
}

handle(params: MissingTranslationHandlerParams): string {
        return this.alternativeJson[params.key];
}



回答2:


I followed the instructions to create a missing translations handler here: https://github.com/ngx-translate/core#how-to-handle-missing-translations

But my version allows passing a default value to the pipe like this

<span>{{"MyTranslateKey" | translate: {Default: "Default Translation"} }}</span>

The default can be a specific string as above, or a variable.

Here is my handler:

import {MissingTranslationHandler, MissingTranslationHandlerParams} from '@ngx-translate/core';

export class MissingTranslationHelper implements MissingTranslationHandler {
  handle(params: MissingTranslationHandlerParams) {
    if (params.interpolateParams) {
      return params.interpolateParams["Default"] || params.key;
    }
    return params.key;
  }
}


来源:https://stackoverflow.com/questions/55662448/ngx-translate-default-text-if-key-is-missing-or-translation-file-is-being-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!