首页 > 解决方案 > PrimeNG 自动完成更改表单数据模型

问题描述

我在 PrimeNG 7.0.0 和 Autocomplete 组件中遇到了一些奇怪的行为。此问题的摘要是,无论我的源JSON对象的结构是什么结构,它都会在选择项目时用此结构覆盖我的FormGroup模型。

我的 FormGroup 对象看起来像:

exportCountry: this.fb.group({
          id: [Validators.required, Validators.maxLength(2)]    //  5/14    a2 UPPERCASE
        }),

这会产生以下 JSON:

{
"exportCountry": {
        "id": ""
      },
}

我的建议源 JSON 如下所示:

{"countries":
[
  {
    "code": "FR",
    "name": "FRANCE"
  },
  {
    "code": "AD",
    "name": "ANDORRA"
  },
  {
    "code": "AE",
    "name": "UNITED ARAB EMIRATES"
  },.....................
]
}

我有一个包含 autoComplete 组件的组件:

<div formGroupName="exportCountry">
  <p-autoComplete [suggestions]="filteredCountriesSingle" [inputId]="type+'countryId'"
                  (completeMethod)="filterCountrySingle($event)" field="code" 
                  [minLength]="1" [inputStyleClass]="'form-control'"
                  formControlName="id">

    <ng-template let-country pTemplate="item">
      <div class="ui-helper-clearfix" style="width: 20em">
        <span>{{country.code}}</span>
        <span> - </span>
        <span>{{country.name}}</span>
      </div>
    </ng-template>
  </p-autoComplete>
</div>

.ts 文件基本上遵循 PrimeNG 展示上的示例,所有这些都正确显示并过滤并显示正确的建议。但是,一旦从选项中选择了一个项目,我的 FormGroup 对象/JSON 将更改为:

"exportCountry": {
        "id": {
          "code": "FR",
          "name": "FRANCE"
        }
      },

我要求根据最初分配的 FormControl 设置所选代码,即

{
"exportCountry": {
        "id": "FR"
      },
}

非常感谢任何帮助。

标签: angulartypescriptprimeng

解决方案


推荐阅读