简体   繁体   中英

Angular ngx-translate - How to set a default value for missing param in translation value

I wish to have a default value for expected parameter in translation value, in case the programmer doesn't providing one.

For Example, for this key in en.json :

"NoRecordsWereFound": "No matching {{records}} were found for your search.",

In the HTML, when providing the records parameters, like here:

<span>
    {{('NoRecordsWereFound' | translate:{ records: 'books' })}}
</span>

I'll get in the Browser:

No matching books were found for your search.

But in case of not providing the parameter, like here:

<span>
    {{'NoRecordsWereFound' | translate}}
</span>

Instead of getting this: No matching {{records}} were found for your search.

I'll get some default value for it, like:

No matching defaultValue were found for your search.

Is it possible? Thanks!

Ngx-translate does not provide such a feature, but you have plenty of options in Angular to achive that. Here are some proposals:

1. Use of *ngIf

You can use *ngIf to reference to a different translation:

<span *ngIf="books">
    {{('NoRecordsWereFound' | translate:{ records: books })}}
</span>
<span *ngIf="!books">
    {{('NoRecordsWereFound Default' | translate )}}
</span>

2. Set default value on init or on error state

You can always set a default value on init of the component or if you did some method call, you can set a default value for erroneous responses.

@Component({
  selector: 'my-app',
  template: `
   <span>
    {{('NoRecordsWereFound' | translate:{ records: books })}}
   </span>
  `,
})
export class AppComponent  {
  books = 'default value';
}

You can also use the store to set default states for different scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM