Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 formControl for select multiple

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?

like image 324
smartmouse Avatar asked Oct 03 '16 15:10

smartmouse


3 Answers

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

like image 97
Daniel Crisp Avatar answered Nov 18 '22 21:11

Daniel Crisp


Working in ionic2 and reactive forms, I was able to validate a multiple select using the validator 'required' only, minlength() did not work. You need to pass null to the model if you want not to pass the validation. Empty array will pass the 'required' validation. A bit weird if you ask me.

like image 40
Becario Senior Avatar answered Nov 18 '22 20:11

Becario Senior


I tried Daniel's answers for my ionic project & it works. Here is a sample if anyone is looking

buildForm() {
    this.registerForm = this.formBuilder.group({
      'contact': ['03007654321', [Validators.required]],
      'agree': [true, Validators.requiredTrue],
      'categories': this.formBuilder.array([]),
      'locations': [[], Validators.required],
    });
  }

and in your HTML template use it like this

<ion-item  >
      <ion-label>Gender</ion-label>
      <ion-select multiple="true" [formControl]="registerForm.controls.locations">
        <ion-option value="f">Female</ion-option>
        <ion-option value="m">Male</ion-option>
      </ion-select>
    </ion-item>

Note: I'm using this in ionic on ion-select but I am guessing it'll work with regular HTML select( ) too.

like image 1
Junaid Avatar answered Nov 18 '22 19:11

Junaid