3

When form is posted, I want to get selected item Name and Value both of an ngSelect dropdown in angular 6.

I have tried getting it with ngModel and with templateVariable, but Selected Name is not returned, I only managed to get Selected Value.

<ng-select
 name="testFunctionID"
 [items]="testFunctions"
 [multiple]="false"
 bindLabel="name"
 bindValue="testFunctionID"
 [(ngModel)]="model.testFunctionID">
</ng-select>

For a list shown in dropdown {Mumbai :1}, {Pune: 2}, {Delhi: 3}, if I select Pune, then I should get "Pune" as well as "2" as output json.

1 Answers1

3

I've not used that package before, but I was curious based on your question, and I think I have an answer for you.

If you look here https://github.com/ng-select/ng-select it indicates in the API Inputs section that

bindValue - Object property to use for selected model. By default binds to whole object.

So I would guess that if you omit the bindValue property, you will have the entire object rather than just the Id.

Also noticed that there is an event you can hook into

(change) - Fired on model change. Outputs whole model


Question author indicated was not able to get the below to work


so you could do something like this.

<ng-select
 name="testFunctionID"
 [items]="testFunctions"
 [multiple]="false"
 bindLabel="name"
 bindValue="testFunctionID"
 [(ngModel)]="model.testFunctionID"
 (change)="model.testFunctionName = $event.name">
</ng-select>

assuming that you want to set a name property on model as well as the Id.

ccamac
  • 496
  • 2
  • 8
  • Your observation helped. Removing "bindValue", I was able to get complete object of selected item. Although second solution didn't work. – Mausam Malviya Jun 06 '19 at 06:10
  • @MausamMalviya glad to hear it. I edited the answer to indicate that the second solution didn't work for you. There is probably some way to get it to work, I'm just not using the right syntax is my guess. But I wanted to leave it in case it sparked an idea for someone else in the future. – ccamac Jun 06 '19 at 11:39
  • @ccamac your second solution works as well. In my case, I needed to bind to the id rather than the object but still needed to get the label to update another field and was able to use the (change) event successfully. thanks! – aks94 Nov 14 '19 at 12:05