Search code examples
typescriptdata-bindingbindingaurelia

Depended dropdowns with Aurelia?


I have an http-api I can use to query about car related stuff with model objects like these coming out of the api:

class Manufacturer {
    id: string;
    name: string;
}

class CarType {
    id: string;
    model: string;
}

class Variant {
    id: string;
    picture: string; // an URL
}

and these methods to get the data:

function getManufacturers(): Promise<Manufacturer[]>;
function getCarTypesOfManufacturer(manufacturerId: string): Promise<CarType[]>;
function getVariantsofCarTypes(maufacturerId: string, carTypeId: string): Promise<Variant[]>;

Now I have to use Aurelia to implement dependend dropdown selections so first someone can select a Manufacturer, then gets all the CarTypes, then all the Variants for that Manufacturer and CarType. After I have this selection, I need to store the retrieved model objects in another model object that will be stored in a database later on.

I have no clue how to structure this with aurelia's binding system. Any Ideas?


Solution

  • you can start by retrieving the list of manufacturers using getManufacturers() and binding the result to the dropdown.

    ts:

    manufacturers: Manufacturer[];
    selectedManufacturerId: string;
    

    html:

    <label>
      Select manufacturer:<br/>
      <select value.bind="selectedManufacturerId">
         option model.bind="null">Choose...</option>
        <option repeat.for="manufacturer of manufacturers"
                model.bind="manufacturer.id">
           ${manufacturer.name}
        </option>
      </select>
    </label>
    

    then observe the selectedManufacturerId property and when it changes retrieve the related car types with getCarTypesOfManufacturer(id).

    ts:

    carTypes: CarType[];
    selectedCarTypeId: string;
    

    html:

    <label>
      Select a car type:<br/>
      <select value.bind="selectedCarTypeId">
         option model.bind="null">Choose...</option>
        <option repeat.for="carType of carTypes"
                model.bind="carType.id">
           ${carType.model}
        </option>
      </select>
    </label>
    

    then do the same for the Variant.

    you can observe the properties (selectedManufacturerId and selectedCarTypeId) using propertyObserver and retrieve the data in the change handler:

    this.bindingEngine
        .propertyObserver(this, 'selectedManufacturerId')
        .subscribe(this.selectedManufacturerIdChanged)