Core: Allow default translation without using MissingTranslationHandler

Created on 2 Jul 2016  路  4Comments  路  Source: ngx-translate/core

When a translation is missing it would be ideal if we could pass in a default fallback string to use if no translation is found (in current or default language).

Suggested syntax:

{{'example.translation.key' | translate:{default:'Example Text'} }}

A specific use case for this is a dropdown list where the first few items (such as item value=0 , text= [Unknown] are translated), but the other items are driven by an external data source and may or may not have a translation.

Most helpful comment

Wouldn't {{ ('example.translation.key' | translate) || 'Example Text' }} work ?

All 4 comments

I use this pattern a lot in the Angular 1 project I'm porting to Angular 2. It's really useful for gracefully defaulting values.

For example if you want to support specific translations, but fallback to a general string

// field = 'name',  collection = 'animals'

let generalFieldTitle = new TranslatePipe()
  .transform(`fields.${field}`);
//=> 'Name'

let specificFieldTitle = new TranslatePipe()
  .transform(`${collection}.fields.${field}`, {default: generalFieldTitle});
//=> 'Animal Name', but it would be 'Name' if collection was 'foobars'

with translations like

en = {
  fields: {
    name: 'Name'
  },
  animals: {
    // This may or may not exist
    name: 'Animal Name'
  }
}

Wouldn't {{ ('example.translation.key' | translate) || 'Example Text' }} work ?

That would be good! However if the translation key is not yet present in the default translation file that outputs as _example.translation.key_

Often you have an error response from the server. Typical Error{Code:111,Message:'yikes'}
In that case: {{ ('example.translation.key' | translate) || 'Example Text' }} would look something like:
{{ ('errorsCodes.'+error.Code | translate) || {{error.Message}} }}. Its a fallback to the default Server message. But it does not parse.
I solved it by:
html:
{{getTrans(theError)}}
component method:
public getTrans(error) { let key = 'errors.' + error.ErrorCode; let translated = this.trans.instant(key); if (translated == key) { return error.Message; } else { return translated; } }

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guysan picture guysan  路  4Comments

louisdoe picture louisdoe  路  3Comments

apreg picture apreg  路  3Comments

bjornharvold picture bjornharvold  路  3Comments

crebuh picture crebuh  路  3Comments