aurelia Binding Binding To Select Elements


Example

Strings Array

When selecting a value in the select dropdown and providing an array of strings, the selected value will be bound to the select element's value property as a string that we can display using string interpolation.

export class MyViewModel {
    animals = [];
    favouriteAnimal = null;

    constructor() {
        this.animals = [
            'Cat',
            'Dog',
            'Fish',
            'Rabbit',
            'Tiger',
            'Bat'
        ];
    }
}
<template>
    ${favouriteAnimal}
    <select name="animals" value.bind="favouriteAnimal">
        <option repeat.for="animal of animals">${animal}</option>
    </select>
</template>

Objects Array

Unlike the above example, when supplying an array of objects, when a value is selected in a dropdown, the model bound to that particular option is the supplied object.

export class MyViewModel {
    animals = [];
    favouriteAnimal = null;

    constructor() {
        this.animals = [
            {label: 'Cat', value: 99},
            {label: 'Dog', value: 493},
            {label: 'Fish', value: 934839200},
            {label: 'Rabbit', value: 8311},
            {label: 'Tiger', value: 22},
            {label: 'Bat', value: 3711}
        ];
    }
}
<template>
    <p>Favourite animal ID: ${favouriteAnimal.value}</p>
    <p>Favourite animal name: ${favouriteAnimal.label}</p>
    <select name="animals" value.bind="favouriteAnimal">
        <option repeat.for="animal of animals" model.bind="animal">${animal.label}</option>
    </select>
</template>