valor-software / ng2-select

Angular based replacement for select boxes
http://valor-software.github.io/ng2-select/
MIT License
675 stars 587 forks source link

Using with reactive forms #832

Open jselesan opened 7 years ago

jselesan commented 7 years ago

Hi there. I'm using ng2-select with reactive forms through "formControlName" and when I get the value of my form, the field value related to the ng2-select is an array of SelectItem. My question is, is there a way to get the "id" of the selected item as the value of the formControl?

VitorHFLopes commented 6 years ago

Hi @jselesan,

Try the .setValue() form control method.

In HTML: <ng-select [items]="items" (selected)="itemSelected($event)"></ng-select>

In TypeScript: itemSelected(item) {

this.form.controls['formControlName'].setValue(item.id);

}

I hope it helps 🙂

showerbeer commented 6 years ago

@VitorHFLopes this solution throws the following error for me

TypeError: selectedItems.map is not a function at SelectComponent.set [as active] (select.js:83)

The setValue function expects an array so it should be

this.form.controls['formControlName'].setValue([item.id]);
VitorHFLopes commented 6 years ago

@showerbeer I couldn't reproduce the error :(

That is an item from my formControls object:

formControlName: ['', Validators.required]

I tried to set a number and a string with no errors