Documentation

 

Selection lists

The translation of the texts of a selection list is a frequent task. The TranslatableOptionList class provides a way to do that easily. Let us assume that we want to create a list of fruits. Tha names of the fruits are stored in JSON files:

// app.hu.json
{
  ...
  "fruits": {
    "apple": "alma",
    "peach": "barack",
    "cherry": "cseresznye",
    "plum": "szilva"
  },
  ...
}

The TranslatableOptionList class provides the list items in an easy way:

@Component({ ... })
export class FruitComponent {

  fruits: TranslatableOptionList;

  constructor(
    private translate: TranslationService
  ) {
    this.fruits = new TranslatableOptionList( translate, 'app.fruits' );
  }
  ...
}

Here 'app.fruits' is the key of the text node. Thereafter the fruit list can be used in the view:

<select>
  <option *ngFor="let fruit of fruits"
          [value]="fruit.value"
          [selected]="fruit.selected">
    {{ fruit.text }}
  </option>
</select>

The following properties are available:

...
  doSomething() {
    ...
    this.fruits.selectedIndex = 2;
    this.fruits.selectedValue = 'cherry';
    ...
    const index: number = this.fruits.selectedIndex;
    const value: string = this.fruits.selectedValue;
    const text: string = this.fruits.selectedText;
    const item: TranslatableOption = this.fruits.selectedItem;
    ...
  }
...

The TranslatableOptionList object will load the appropriate translation texts when the user changes the current language.