Reputation: 121
I am trying to populate a form which has a few PrimeNg dropdowns. For simplicity let me use example similar to what is on their web site.
<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'}
];
So suppose user from table with his trips selects a row for edit. It corresponds to some complex object, which contains a City property. We need to programmatically select say Rome in that dropdown on the form.
I tried to do:
this.myFormGroup.get("selectedCity").setValue('Rome');
tried:
this.myFormGroup.get("selectedCity").patchValue('Rome');
tried adding to html:
optionLabel="name"
Nothing gets selected.
Any advice how to do it properly?
I assume I should not add
[(ngModel)]="selectedCity"
and do:
this.selectedCity='Rome';
Using Angular6 and PrimeNG 6.1.2.
Upvotes: 5
Views: 15500
Reputation: 4854
First of all it should be clear that; whatever the options
array contains they are the values set to the FormControl
.
In this case form control values are city objects because cities
array contains objects.
In order to set form control value programmatically, the value must be one of the elements from options
array.
So, if you want to set Istanbul
as selected you must set exact same object from cities
array (particularly, cities[3]
)
It can be done in this way;
this.myFormGroup.get("selectedCity").setValue(this.cities.find(city => city.name === "Istanbul"));
As a side note optionLabel="name"
only indicates which field from city objects to use as display value, that's all.
Here is a demo: https://stackblitz.com/edit/angular-6-template-6yu6jz
Upvotes: 8