Hani Hani - 3 months ago 26
TypeScript Question

angular2, binding a select element to another select element's selection

I have two

<select>
elements:

<select [(ngModel)]="model.SelectedSomeValue">
<option *ngFor="let someValue of model.SomeValues">{{ someValue }}</option>
</select>

<select [(ngModel)]="model.SelectedSomeValue.SelectedOtherValue">
<option *ngFor="let otherValue of model.SelectedSomeValue.OtherValues">{{ otherValue }}</option>
</select>


It seems that you can't bind the second
<select>
to
model.SelectedSomeValue
as it never populates correctly. It contains the
value
, although by specifying
[value]="value"
one would expect that the object reference is stored but that's not the case. So how can we do a binding between two
<select>
elements?

Answer

If I understand your question, you want one selector to choose a category and a second selector to choose the options within the category? So if you change selector 1, then you would get a different list of items in selector 2?

If so, then check this Plunker: https://embed.plnkr.co/UErCcJeX5ply1BXSjweY/

There was a bug in the beta releases that prevented ngModel from working on some browsers so make sure you upgrade at least to RCs (the plunker is RC5).

Essentially, the code is this:

<p><select [(ngModel)]="selected">
    <option value=""></option>
    <option *ngFor="let datum of data" [ngValue]="datum">{{datum.name}}</option>
</select>

<p><select [(ngModel)]="selected2">
    <option *ngFor="let val of selected?.value" [ngValue]="val">{{val}}</option>
</select>

And the component has a list of objects in data and a place to store the selected values in selected and selected2. The first selector uses data to display options (and stores the object with the subcatagories as the option value) and is bound to the selected variable. The second second selector gets uses the selected.values to create options, and stores the selection in selected2.