以模型驱动形式设置 primeng 下拉列表的值

use*_*152 5 typescript primeng angular

我正在尝试填充一个包含一些 PrimeNg 下拉菜单的表单。为了简单起见,让我使用类似于他们网站上的示例。

<form [formGroup]="myFormGroup">
  <p-dropdown [options]="cities" formControlName="selectedCity"></p-dropdown>
</form>
Run Code Online (Sandbox Code Playgroud)
this.cities = [
  {name: 'New York', code: 'NY'},
  {name: 'Rome', code: 'RM'},
  {name: 'London', code: 'LDN'},
  {name: 'Istanbul', code: 'IST'},
  {name: 'Paris', code: 'PRS'}
];
Run Code Online (Sandbox Code Playgroud)

因此,假设用户从行程表中选择一行进行编辑。它对应于一些复杂的对象,其中包含 City 属性。我们需要以编程方式在表单的下拉列表中选择罗马。

我尝试这样做:

this.myFormGroup.get("selectedCity").setValue('Rome');
Run Code Online (Sandbox Code Playgroud)

尝试过:

this.myFormGroup.get("selectedCity").patchValue('Rome');
Run Code Online (Sandbox Code Playgroud)

尝试添加到html:

optionLabel="name"
Run Code Online (Sandbox Code Playgroud)

什么都没有被选中。

有什么建议如何正确地做吗?

我想我不应该添加

[(ngModel)]="selectedCity"
Run Code Online (Sandbox Code Playgroud)

并做:

this.selectedCity='Rome';
Run Code Online (Sandbox Code Playgroud)

使用 Angular6 和 PrimeNG 6.1.2。

ysf*_*ysf 8

首先应该明确的是;无论options数组包含什么,它们都是设置为 的值FormControl

在这种情况下,表单控件值是城市对象,因为cities数组包含对象。

为了以编程方式设置表单控件值,该值必须是options数组中的元素之一。

因此,如果您想设置为选定的,则必须从数组Istanbul中设置完全相同的对象(特别是, )citiescities[3]

可以这样做;

this.myFormGroup.get("selectedCity").setValue(this.cities.find(city => city.name === "Istanbul"));
Run Code Online (Sandbox Code Playgroud)

作为旁注,optionLabel="name"仅指示城市对象中的哪个字段用作显示值,仅此而已。

这是一个演示:https ://stackblitz.com/edit/angular-6-template-6yu6jz