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

Share:
11,098

Related videos on Youtube

1Z10
Author by

1Z10

Updated on June 04, 2022

Comments

  • 1Z10
    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 variable first, 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.