Ng2-select: How to use with formControlName?

Created on 24 Jul 2017  路  5Comments  路  Source: valor-software/ng2-select

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

Most helpful comment

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

All 5 comments

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

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

@nellyigiebor thanks

@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: 1__proto__: Array(0)

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

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

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Garybhardwaj picture Garybhardwaj  路  3Comments

rkralston picture rkralston  路  3Comments

carstenschaefer picture carstenschaefer  路  5Comments

jenb34 picture jenb34  路  5Comments

Cadenei picture Cadenei  路  4Comments