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?
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With