1

In PrimeNG dropdown is there any work around option to add 'optionValue'.

There is currently an optionLabel property but no way to choose a property to represent value so you end up with the whole object. Basically in PrimeNG dropdown, trying to pass string rather than entire object

Antikhippe
  • 6,316
  • 2
  • 28
  • 43
ShaMoh
  • 1,490
  • 3
  • 18
  • 34

2 Answers2

0

I believe current version of PrimeNG (11.x) has exactly what you are looking for, which as you say is "optionValue". One interesting behavior is that when you use optionLabel, the return value becomes an object. Let's say I'm working with the following:

component.ts

places = [
{name: "New York", label: "Work", value: 200},
{name: "Michigan", label: "Home", value: 100} 
];

selectedPlace;

HTML Scenario 1: Default Behavior

<p-dropdown [options]="places" 
 [(ngModel)]="selectedPlace" 
 [ngModelOptions]="{standalone: true}" 
 placeholder="Select">
</p-dropdown> <!-- Shows Work or Home looking up 'label' -->
<pre>{{selectedPlace}}</pre> <!-- shows 100 or 200 depending on selection -->

HTML Scenario 2: Specify custom label

<p-dropdown [options]="places" 
[(ngModel)]="selectedPlace" 
[ngModelOptions]="{standalone: true}" 
placeholder="Select" 
optionLabel="name">
</p-dropdown> <!-- Shows New York or Michigan looking up 'name' -->
<pre>{{selectedPlace | json }}</pre> <!-- SHOWS ENTIRE SELECTED OBJECT DEPENDING ON SELECTION -->

HTML Scenario 3: Specify custom value

<p-dropdown [options]="places" 
[(ngModel)]="selectedPlace" 
[ngModelOptions]="{standalone: true}" 
placeholder="Select" 
optionValue="name">
</p-dropdown> <!-- Shows Home or Work looking up 'label' -->
<pre>{{selectedPlace }}</pre> <!-- Shows New York or Michigan depending on selection -->

HTML Scenario 4: Specify custom label AND custom value

<p-dropdown [options]="places" 
[(ngModel)]="selectedPlace" 
[ngModelOptions]="{standalone: true}" 
placeholder="Select" 
optionLabel="name" 
optionValue="value">
</p-dropdown> <!-- Shows New York or Michigan looking up 'name' -->
<pre>{{selectedPlace | json }}</pre> <!-- Shows 100 or 200 depending on selection -->

So as you can see, using the current primeNG (11.x), if you are using optionLabel, you can use optionValue to only get the string, because if you don't specify optionValue, you will get an entire object.

Jason
  • 657
  • 7
  • 13
-1

According to the documentation, the property dataKey should do what you want, but I didn't manage to get it work

dataKey : A property to uniquely identify a value in options.

Moussa
  • 4,066
  • 7
  • 32
  • 49