p-dropdown with reactive forms not binding correctly
Asked Answered
M

2

7

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;

            }
Mandel answered 26/2, 2019 at 21:46 Comment(2)
[options]=icostcentre.result will do the job ,if not then please provide a stackblitz I will help you outExacting
i get error "Cannot read property 'result' of undefined"Mandel
G
8

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>
Gosling answered 26/2, 2019 at 21:55 Comment(0)
B
5
<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" 
  optionValue="costCenter">
</p-dropdown>

You can use optionValue to set particular value to formControl instead of Object.dataKey property used to uniquely identify a value in options.

Belletrist answered 26/3, 2021 at 5:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.