Crowdpleasr
Crowdpleasr

Reputation: 4044

Default option for Select not working (reactive form)

I'm trying to set the default value for a Select in a Reactive form, but not having any luck. I saw a lot of discussion on this topic in Stackoverflow, and it seems all I need to do is add [selected]="(expression)" but the solutions haven't worked for me. What am I doing wrong?

// Note: itm[6] == ["Option1", "Option2, "Option3"], itm[5]=="Option2" (i.e., the default)

<select name="foo" formControlName="foo">
  <option *ngFor="let g of itm[6]; let idx = index" [value]="idx" [selected]="g==itm[5]">{{g}}</option>
</select>

Upvotes: 0

Views: 1722

Answers (3)

Crowdpleasr
Crowdpleasr

Reputation: 4044

It turns out that my problem was as per my original post I had: [value]=idx, so I either needed to change that to [value]=g or else use the index number in setValue or patchValue

Upvotes: 1

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24406

with reactive form you can did this by set the form control itself rather than try set the select attribute , any change of the value of the form control will reflect to the html , her any change of the value will set the option to be selected and in case the value was not in the option will look like empty.

this.form.get('foo').setValue('Option2')

demo 🚀🚀

Upvotes: 1

Armin
Armin

Reputation: 149

You can try by adding [selected]="g==='Option2'" to select option. Or you can patch default value to formcontrol

this.myForm.patchValue({ foo : 'Option2' });

Upvotes: 2

Related Questions