Angular2 formControl for select multiple

smartmouse picture smartmouse · Oct 3, 2016 · Viewed 17.3k times · Source

I'm using Sematinc-UI and Angular2 ReactiveFormsModule form and i'd like to use [formControl] for select multiple.

If i use select it works with no problems:

        <select class="ui fluid dropdown" [formControl]="myForm.controls.category">
            <option *ngFor="let item of categories" value="{{item}}">{{item}}</option>
        </select>

If i use select multiple it doesn't work:

        <select multiple="" class="ui fluid dropdown" [formControl]="myForm.controls.category">
            <option *ngFor="let item of categories" value="{{item}}">{{item}}</option>
        </select>

I get this error:

core.umd.js:3462 EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/components/category.component.js class CategoryComponent - inline template:0:1701 caused by: values.map is not a function

What could be the problem?

Answer

Daniel Crisp picture Daniel Crisp · Nov 2, 2016

I got it working. The trick was to make sure that the value is always an array, even when nothing is selected.

<select multiple class="ui fluid dropdown" [formControl]="myForm.controls.category">
    <option *ngFor="let item of categories" [ngValue]="item">{{item}}</option>
</select>

When creating the FormControl make sure the blank value is an empty array, rather than '' or undefined.

this.control = new FormControl([]);

I'm not using Semantic-UI, just standard Angular 2