[FIXED] p-dropdown with reactive forms not binding correctly

Issue

I am using primeng dropdown and having a hard time biding my object to the dropdown. it does populate the dropdown with empty items.. not sure how to specify the field name.

HTML

<div class="form-group col-xs-3 col-md-3"
                                     [ngClass]="{
                                     'has-error':((ersaForm.get('costCenter').touched || ersaForm.get('costCenter').dirty ) && 
                                      !ersaForm.get('costCenter').valid) || (ersaForm.get('costCenter').value.cost_center_name == '')
                                     }">
 <label for="costCenterId" class="control-label">Cost Center</label>
 <p-dropdown [options]="iCostCenter" styleClass="form-control" formControlName="costCenter" placeholder="Cost Center (required)" id="costCenterId" name="costCenter"  dataKey="cost_center_id">
</p-dropdown>

object

    {
  "result": [
    {
      "cost_center_id": 0,
      "cost_center_name": "0"
    },
    {
      "cost_center_id": 1,
      "cost_center_name": "1"
    },
    {
      "cost_center_id": 2,
      "cost_center_name": "2"
    },
}

TS

    export interface ICostCenter{

        cost_center_id: string,
        cost_center_name: string
    }

   iCostCenter: ICostCenter[];
    this._appParams.getAllCostCenters()
            .subscribe(
            data => {
                this.iCostCenter = data.result;

            }

Solution

If you look at the official documentation it says that you need to use optionLabel property if you are binding to a collection of arbitrary objects.

<p-dropdown [options]="iCostCenter" optionLabel="cost_center_name" styleClass="form-control" formControlName="costCenter" placeholder="Cost Center (required)" id="costCenterId" name="costCenter"  dataKey="cost_center_id">
</p-dropdown>

Answered By – AleŇ° Doganoc

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published