【问题标题】:p-dropdown with reactive forms not binding correctly具有反应形式的 p-dropdown 未正确绑定
【发布时间】:2019-07-20 12:50:26
【问题描述】:

我正在使用primeng 下拉菜单,并且很难将我的对象与下拉菜单绑定。它确实用空项目填充下拉列表。不知道如何指定字段名称。

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>

对象

    {
  "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;

            }

【问题讨论】:

  • [options]=icostcentre.result 会完成这项工作,如果没有,请提供一个 stackblitz 我会帮助你
  • 我收到错误“无法读取未定义的属性‘结果’”

标签: angular typescript primeng primeng-dropdowns


【解决方案1】:
<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>

您可以使用optionValue 将特定值设置为formControl,而不是用于唯一标识选项中的值的Object.dataKey 属性。

【讨论】:

    【解决方案2】:

    如果您查看official documentation,它表示如果您要绑定到任意对象的集合,则需要使用optionLabel 属性。

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

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 2018-02-15
      • 1970-01-01
      • 2023-03-12
      • 2019-04-06
      • 2014-07-11
      • 2021-04-02
      • 2019-10-12
      • 2022-07-27
      相关资源
      最近更新 更多