以模型驱动形式设置 primeng 下拉列表的值
Set value of primeng dropdown in model driven form
我正在尝试填充一个有几个 PrimeNg 下拉菜单的表单。
为简单起见,让我使用类似于他们网站上的示例。
<form [formGroup]="myFormGroup">
<p-dropdown [options]="cities" formControlName="selectedCity"></p-dropdown>
</form>
this.cities = [
{name: 'New York', code: 'NY'},
{name: 'Rome', code: 'RM'},
{name: 'London', code: 'LDN'},
{name: 'Istanbul', code: 'IST'},
{name: 'Paris', code: 'PRS'}
];
所以假设来自 table 的用户和他的行程 select 是一行需要编辑的。
它对应于一些复杂的对象,其中包含一个城市属性。
我们需要以编程方式 select 在表单的下拉菜单中说罗马。
我试过:
this.myFormGroup.get("selectedCity").setValue('Rome');
尝试过:
this.myFormGroup.get("selectedCity").patchValue('Rome');
尝试添加到 html:
optionLabel="name"
什么都没有 selected。
有什么正确的建议吗?
我想我不应该添加
[(ngModel)]="selectedCity"
并做:
this.selectedCity='Rome';
使用 Angular6 和 PrimeNG 6.1.2。
首先要明确的是;无论 options
数组包含什么,它们都是设置为 FormControl
.
的值
在这种情况下,表单控件值是城市 objects 因为 cities
数组包含对象。
为了以编程方式设置表单控件值,该值必须是 options
数组中的元素之一。
因此,如果您想将 Istanbul
设置为选中状态,则必须从 cities
数组(特别是 cities[3]
)
中设置完全相同的对象
可以这样做;
this.myFormGroup.get("selectedCity").setValue(this.cities.find(city => city.name === "Istanbul"));
附带说明 optionLabel="name"
仅指示城市对象中的哪个字段用作显示值,仅此而已。
这是一个演示:https://stackblitz.com/edit/angular-6-template-6yu6jz
我正在尝试填充一个有几个 PrimeNg 下拉菜单的表单。 为简单起见,让我使用类似于他们网站上的示例。
<form [formGroup]="myFormGroup">
<p-dropdown [options]="cities" formControlName="selectedCity"></p-dropdown>
</form>
this.cities = [
{name: 'New York', code: 'NY'},
{name: 'Rome', code: 'RM'},
{name: 'London', code: 'LDN'},
{name: 'Istanbul', code: 'IST'},
{name: 'Paris', code: 'PRS'}
];
所以假设来自 table 的用户和他的行程 select 是一行需要编辑的。 它对应于一些复杂的对象,其中包含一个城市属性。 我们需要以编程方式 select 在表单的下拉菜单中说罗马。
我试过:
this.myFormGroup.get("selectedCity").setValue('Rome');
尝试过:
this.myFormGroup.get("selectedCity").patchValue('Rome');
尝试添加到 html:
optionLabel="name"
什么都没有 selected。
有什么正确的建议吗?
我想我不应该添加
[(ngModel)]="selectedCity"
并做:
this.selectedCity='Rome';
使用 Angular6 和 PrimeNG 6.1.2。
首先要明确的是;无论 options
数组包含什么,它们都是设置为 FormControl
.
在这种情况下,表单控件值是城市 objects 因为 cities
数组包含对象。
为了以编程方式设置表单控件值,该值必须是 options
数组中的元素之一。
因此,如果您想将 Istanbul
设置为选中状态,则必须从 cities
数组(特别是 cities[3]
)
可以这样做;
this.myFormGroup.get("selectedCity").setValue(this.cities.find(city => city.name === "Istanbul"));
附带说明 optionLabel="name"
仅指示城市对象中的哪个字段用作显示值,仅此而已。
这是一个演示:https://stackblitz.com/edit/angular-6-template-6yu6jz