Home > Mobile >  How to select value by index in Reactive Form Angular 12?
How to select value by index in Reactive Form Angular 12?

Time:04-13

I have below code

<select formControlName="test">
   <option value="1">A</option>
   <option value="2">B</option>
   <option value="1">C</option>
   <option value="1">D</option>
</select>

I have same value. How to select by index. I want to default selected as C in typescript.

CodePudding user response:

<select name="test">
   <option *ngFor="let opt of options; let index = index" [value]="opt.value" [selected]="index === 2">{{opt.label}}</option>
</select>

in your ts:

options = [
  {
    value: 1,
    label: 'A'
  },
  {
    value: 2,
    label: 'B'
  },
  {
    value: 1,
    label: 'C'
  },
  {
    value: 1,
    label: 'D'
  },
]

stackblitz

CodePudding user response:

You could make use of selected.

<select name="test">
   <option value="1">A</option>
   <option value="2">B</option>
   <option value="1" selected="selected">C</option>
   <option value="1">D</option>
</select>
  • Related