Reputation: 1973
I have a form with a form control currency. A currency object looks like this {id: string; symbol: string}; On init, the currency select iterates over an array of currencies; After a condition is verified I need to patch a currency object to my select
const currency = {id: '2', symbol: 'CAD'}
this.currency.patchValue(currency);
console.log(this.currency.value);
the output is correct: {id: '2', symbol: 'CAD'}, but there is no selected option in my dropdown
<select class="generalDropdown currencies" formControlName="currency">
<option value=null disabled>CUR</option>
<option *ngFor="let currency of allCurrencies" [value]="currency.id"> {{currency.symbol}}
</option>
</select>
Upvotes: 0
Views: 1021
Reputation: 27419
Initially you are assigning [value]="currency.id" to select element. But when you are patching value to formControl we are setting object value, due to which select not showing bind value. You can fix the issue by patch currencyId instead of patching whole object.
const currency = {id: '2', symbol: 'CAD'}
this.currency.patchValue(currency.id);
OR
You need to assign whole object to ngValue. Then to match object reference we need to use compareWith function along with select.
<select class="generalDropdown currencies" [compareWith]="compareFn" formControlName="currency">
<option value=null disabled>CUR</option>
<option *ngFor="let currency of allCurrencies" [value]="currency"> {{currency.symbol}}
</option>
</select>
component.ts
compareFn(c1: any, c2: any): boolean {
return c1 && c2 &&( c1.id === c2.id || c2 === c1.id);
}
Upvotes: 2
Reputation: 2708
Use ngValue
instead of value
on the options. When you patch the form, use the value instead of an object.
<form [formGroup]="myForm" (ngSubmit)="submit(myForm.value)">
<label>Currency: </label>
<select formControlName="currency">
<option [ngValue]="1">USD</option>
<option [ngValue]="2">CAD</option>
<option [ngValue]="3">EUR</option>
</select>
<br>
<button type="submit">Submit</button>
</form>
Example use of patch()
:
selectCAD() {
this.myForm.controls.currency.patchValue(2);
}
Here's a stackblitz that demonstrates
Upvotes: 0