Reputation: 6141
I have a dropdown mat-select that is created dynamically via Form Builder and displayed in a series of loops and supplied an initial value, but the dropdown itself is not actually set.
const control = this.formBuilder.control(value, validators);
myForm.addControl(id, control);
debugger;
The html to display is
<mat-select [value]="getFormValue(input.id)" [formControlName]="input.name" [placeholder]="idForDebug">
<mat-option *ngFor="let option of input.dropdownOptions" [value]="option.fieldValue">
{{option.display}}
</mat-option>
</mat-select>
I also tried the above with/without the [value] param supplied, since I'm already using [formControlerName]. Same behavior each way
getFormValue is defined as
public getFormValue(id) {
debugger;
return myForm.get(id).value;
}
I have confirmed via debugger that the value and id match both when I create the control and in the getFormValue method. If all the data is there and supplied, why is the dropdown value not set? What would I be missing?
Confirmed via console and debugger all values and IDs match in all 3 locations above, yet dropdown is not pre-selected.
-- I created a simplified version of this on stackblitz https://stackblitz.com/edit/angular-pggkbk
In this live example I would expect the dropdown to be pre-populated with the value 1
since that's what is supplied when the control is created via
const control = this.formBuilder.control(1, []);
solved
I feel silly, the values coming in from the db were as Strings, so when I set the dropdown value to the string but compared it to the [value] from dropdownOptions which was a numbers, they never matched.
ParseInt(value) and everything worked out gravy
Upvotes: 2
Views: 1123
Reputation: 58019
Really I don't understand your question. I imagine you has an array of inputs like
inputs=[{
name:'select',
dropdownOptions:[
{fieldValue: 'steak-0', display: 'Steak'},
{fieldValue: 'pizza-1', display: 'Pizza'},
{fieldValue: 'tacos-2', display: 'Tacos'}
]
}]
And a variable "data" with the values
data:any={select:'pizza-1'}
If you use a variable form in a NgOnInit you can use some like
form=new FormGroup({})
ngOnInit()
{
this.inputs.forEach(x=>{
this.form.addControl(x.name,new FormControl(this.data[x.name]))
})
}
well, you can give value to the formControl with the first value of option
this.form.addControl(x.name,new FormControl(x.dropdownOptions[0].fieldValue))
Then you display the form like
<form [formGroup]="form">
<div *ngFor="let input of inputs">
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select [formControlName]="input.name" [placeholder]="idForDebug">
<mat-option *ngFor="let option of input.dropdownOptions" [value]="option.fieldValue">
{{option.display}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</form>
take a look to the stackblitz. remember, to give value a FormControl not use [value], just change the value of control. You can make when you create the form, or using setValue
Upvotes: 1