How do I set primeNg dropdown selected value as the id of the object instead of the entire object

Viewed 7111

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?

3 Answers

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' }

I wasn't able to set a value with the default primeNG dropdown component. To try and keep it DRY I instead created a helper service that creates the array based off a collection.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class HelperService {

  constructor() { }

  getDropdownValuesFromArray(collectionArray : any[]): any[] {
    let typeArray: any[] = [];
    for(let i = 0; i< collectionArray.length; i++) {
      typeArray.push({});
      typeArray[i].label = collectionArray[i].Name;
      typeArray[i].value = collectionArray[i].Code;
    }
    return typeArray;
  }
}

Seems like an oversight from primeNG, hopefully they add it.

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.

Related