Angular 5 *ngFor SELECT: how to set an option SELECTED if it's the first?
11,098
Try this
<select [formControlName]="question.id">
<option *ngFor="let answer of answers; let i = index" [value]="answer.name" [selected]="i == 0">
{{answer.name}}
</option>
</select>
working example
Related videos on Youtube
Author by
1Z10
Updated on June 04, 2022Comments
-
1Z10 almost 2 years
I'm building a simple form looping through a list of questions, and for each question through the list of its answers. Now, since I'm building a
SELECT
form control, listing the available options through a*ngFor
, I would like to make the first option the default one, in other words, make it SELECTED based on the value of the local variablefirst
, but I'm not getting why the following approach is not working.<select [formControlName]="question.id"> <option *ngFor="let answer of answers; first as isFirst" [value]="answer.name" [selected]="isFirst"> {{answer.name}} </option> </select>
The suggested questions didn't resolve my problem. Tried replacing [selected] with [attr.selected] but didn't work.
-
bugs almost 6 yearsPossible duplicate of assign select initial value in angular4
-
Srigar almost 6 yearsCheck this stackoverflow.com/a/40326743/2878777
-