Search code examples
htmlselectaurelia

Using templates as select option name in Aurelia


I have a select in Aurelia that looks like

                        <select
                            name="car"
                            value.bind="car">
                            <option repeat.for="car of cars" model.bind="car.id">
                                ${car.name}
                            </option>
                        </select>

Now, I want to display the name of the car, based on a condition, like

                            <template if.bind="mYcondition">
                                ${car.name}
                            </template>
                            <template if.bind="!mYcondition">
                                ${car.name} - ${getCarSeries.get(car.id)}
                            </template>

If I put this together, looks like

                        <select
                            name="car"
                            value.bind="car">
                            <option repeat.for="car of cars" model.bind="car.id">
                                <template if.bind="mYcondition">
                                     ${car.name}
                                </template>
                                <template if.bind="!mYcondition">
                                    ${car.name} - ${getCarSeries.get(car.id)}
                                 </template>
                            </option>
                        </select>

In this case, my IDE complains because of Element template is not allowed here.

Any way around it?


Solution

  • You can add a get method to your viewmodel that returns the display name, like so:

    public get getDisplayName(car) {
      if (mYcondition) {
        return car.name;
      } else {
        return car.name + " - " this.getCarSeries.get(car.id);
      }
    }
    

    And then call that in your view:

    <select name="car" value.bind="selectedCar">
      <option repeat.for="car of cars" model.bind="car.id">
         ${getDisplayName(car)}
       </option>
    </select>