NG: 7.2.15
Scenario:
I am using multiple p-dropdowns in a reactive form. The data [options] of the dropdowns are retrieved by the api in an array of objects {id: number, name: string}. However the form data retrieved by the api only has an ID that i can use to set the initial selection of the dropdown. When an additional selection is made, the from control is bound to the entire object {id: number, name: string}, instead of just the ID.
Question:
Is there a way that I can bind a list of objects to the dropdown and have the dropdown use the id for all binding purposes?
Here is a simplified version:
https://stackblitz.com/edit/angular-nta7y9
TEMPLATE:
Code: Select all
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<label>What is your favorite soda?</label>
<p-dropdown
[options]="objects"
optionLabel="name"
formControlName="favSoda"
dataKey="id"
placeholder="Select"
></p-dropdown>
<button type="submit">Submit</button>
</form>
Code: Select all
myForm: FormGroup = new FormGroup({});;
objects: Array<{id: number, name: string}> = [
{
id: 0,
name: "Coke"
},
{
id: 1,
name: "Diet Coke"
},
{
id: 2,
name: "Mountain Dew"
},
{
id: 3,
name: "Dr. Pepper"
},
{
id: 4,
name: "Sprite"
},
]
constructor(
private _fb: FormBuilder,
){
this.buildForm();
}
getFavSoda = () => this.myForm.get('favSoda').value
private buildForm(): void {
this.myForm = this._fb.group({
favSoda: [1, Validators.required]
});
}
1.) The binding of the objects
2.) The form control is updated with the corresponding selected object
Problems:
1.) I am setting the initial value of favSoda to 1 (Diet Coke), I would expect the dropdown to be able to identify that I want Diet Coke selected by default, and not have the placeholder text be displayed at all.
2.) After a selection is made the formControl is bound to the entire object, example:
Code: Select all
//actual output = {1, "Diet Coke"}
//desired output = 1
this.myForm.get('favSoda').value