The TranslatableTextList class makes easy to handle several text items in the controller code. For example you want to use these texts:
|
|
You can do it like that:
@Component({...})
export class ShopComponent {
private texts: TranslatableTextList;
constructor(
private translate: TranslationService
) {
this.texts = new TranslatableTextList( this.translate, keyList );
}
...
}
The key list can be a string, a string array or an object.
In that case the text list will contain one item only, not very useful. Anyway, it can be used like that:
...
constructor(
private translate: TranslationService
) {
this.texts = new TranslatableTextList( this.translate, 'seasons.spring.name' );
}
doSomething() {
const spring: string = this.texts.get( 'seasons.spring.name' );
...
}
...
However, when the key identifies a node in the translations, all items of the node are returned. The items can be accessed using the property names:
...
constructor(
private translate: TranslationService
) {
this.texts = new TranslatableTextList( this.translate, 'index.seasons' );
}
doSomething() {
const summer: string = this.texts.get( 'summer' );
const winter: string = this.texts.get( 'winter' );
...
}
...
Similar to the previous case, but several items can be fetched at a time:
...
constructor(
private translate: TranslationService
) {
this.texts = new TranslatableTextList(
this.translate, [
'seasons.summer.name',
'seasons.autumn.name',
'seasons.winter.name',
'index.seasons'
] );
}
doSomething() {
const autumn: string = this.texts.get( 'seasons.autumn.name' );
const fall: string = this.texts.get( 'autumn' ); // from index,seasons.autumn
...
}
...
The most practical use case, as the object can be used to map the text keys to shorter ones:
...
constructor(
private translate: TranslationService
) {
this.texts = new TranslatableTextList(
this.translate, {
'seasons.summer.name': 'summer',
'index.seasons.autumn': 'fall',
'seasons.winter.name': 'winter'
} );
}
doSomething() {
const summer: string = this.texts.get( 'summer' );
const autumn: string = this.texts.get( 'fall' );
const winter: string = this.texts.get( 'winter' );
...
}
...
Parameters are allowed as usual, e.g.:
// app.en.json
{
...
"shop": {
"offer": "Offer of the day: buy {{ buy }} pay {{ pay }}!",
"special": "Every {{0}} film is {{1}}% off!",
"sale": "The sale still lasts for {{ 0 }} days."
},
...
}
And then:
@Component({...})
export class ShopComponent {
private texts: TranslatableTextList;
constructor(
private translate: TranslationService
) {
this.texts = new TranslatableTextList(
this.translate,
{
'app.shop.offer': 'offer',
'app.shop.special': 'special',
'app.shop.sale': 'lasts'
}
);
}
doSomething() {
const dailyOffer: string = this.texts.get( 'offer', { buy: 3, pay: 2 } );
const specialOffer: string = this.texts.get( 'special', [ 'Jackie Chan', 20 ] );
const specialLasts: string = this.texts.get( 'lasts', 4 );
...
}
}