I am data binding a collection to the prime NG dropdown.
<p-dropdown [options]="statusTypes" formControlName="StatusTypeCode" optionLabel="Name">
</p-dropdown>
I am setting the formControlName to this dropdown, which works great. The only problem is that the form sets the entire object (example: statusTypes[2]). I want the form to specify a value for the selected value, instead of the entire object (example: statusTypes[2].StatusTypeCode)
I know I can recreate the options before setting them...
this.statusTypes= [];
for (let statusType of this.allStatusTypes) {
this.statusTypes.push({ label: (statusType.Name), value: statusType.StatusTypeCode });
}
but then I have to do that on every drop down collection!
Is there any way in the HTML to just specify the value of the dropdown equal to a property (example: optionValue="StatusTypeCode") so I can have the form populate with the id instead of the entire object?
I don't know when they updated this but, in PrimeNG documentation Dropdown has the property "optionValue" which will solve this problem. I had smiilar problem wanted to select object of id from an array and this is what I got
<p-dropdown id="dropdown" inputId="dropdown" optionValue="id" [autoDisplayFirst]="false" [options]="cities" formControlName="id" optionLabel="name"></p-dropdown>
now it will select { id: '1' }
instead of { id: '1', name: 'cityName' }
Unfortunately you can't change the way PrimeNG dropdown uses the value, by default dropdown uses the entire object from the Array of objects; PrimeNG only allow to change the label by optionLabel property. This is because all PrimeNG components uses it's api SelectItem. For your question what you can do is to create another array from your custom array just like you did in you description.
For the moment there is no option for custom value. I suggest you to keep using the entire object with ngModel if your scenario you are not going to use multiple dropdown produced from iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With