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.
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;
}
}
Most helpful comment
Wouldn't
{{ ('example.translation.key' | translate) || 'Example Text' }}work ?