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

How to use with formControlName? #854

Open bolerap opened 6 years ago

bolerap commented 6 years ago

Hi all. As title, I want to use ng2-select with formControlName property for form? how can i use with? Thanks.

asce4s commented 6 years ago

I have solved this by using a workaround

 <ng-select [allowClear]="true"
                   [items]="designations"
                   [disabled]="disabled"
                   placeholder="No Designation selected"
                   (data)="select2.designation=($event.id)"
              ></ng-select>
<input type="hidden" [(ngModel)]="select2.designation" formControlName="id">

so basically what you have to do is bind a variable into a hidden field and change that variable value on 'data' event

nellyigiebor commented 6 years ago

another way is to create a private function in your component to get and bind the value to your formControlname; like so, private getSelectedValue(event) { this.[formgroupname].controls[forControlname].setValue(event.id); }

hope this help

yrang commented 6 years ago

@nellyigiebor thanks

RRGT19 commented 5 years ago

@thanhngvpt I have used formControlName and it works.

HTML

<ng-select [allowClear]="true"
                   [items]="items"
                   formControlName="nameOfCountry"
                   placeholder="Select one please">
</ng-select>

The value saved will be something like this:

[SelectItem] 0: SelectItemid: "Barcelona" text: "Barcelona" proto: Objectlength: 1proto: Array(0)

To access to the "text" value I have done this:

TS console.log(this.registerForm.controls.nameOfCountry.value[0].text);

dstj commented 5 years ago

Using [value] in <ng-option> or [bindValue] for a [items] list also works, for example:

<ng-select formControlName="billingCycle">
    <ng-option [value]="'1'">Monthly</ng-option>
    <ng-option [value]="'2'">Quarterly</ng-option>
    <ng-option [value]="'3'">Yearly</ng-option>
</ng-select>

or

<ng-select formControlName="billingCycle" [items]="items" [bindValue]="'id'"></ng-select>

items = [
   { id: 1, label: 'Monthty' }
   { id: 2, label: 'Quarterly' },
   { id: 3, label: 'Yearly' },
]

Your form will get the proper value set, not the object.