0

Having a dropdown with option populated using ngFor in angular 2 code. I need any particular option at any given index to be selected by default.

I have used [attr.selected]="i == 0" ,but it selects last option instead first one.

Here is My code

<select id="roles" required formControlName="userRole">
    <option *ngFor="let roles of URoles;let i = index" [attr.selected]="(i==0)" [value]="roles._id">{{ roles.name }}</option>
</select>

What could be the problem ? Why first option not selected ?

sandeep
  • 175
  • 2
  • 16
  • why to use ng-container in this case? just add the *ngFor to the option element – Raed Khalaf Mar 06 '18 at 10:33
  • maybe this answer could be helpful https://stackoverflow.com/questions/37663158/set-initially-selected-item-in-select-list-in-angular2 – mrebval Mar 06 '18 at 10:34

3 Answers3

0

As per my understanding select is working as it should work . so an easy solution will be

<ng-container *ngFor="let roles of universityAllRoles;let first = first"<option [attr.selected]="first" [value]="roles._id">{{ roles.name }}</option></ng-container>
Aswin
  • 1
  • 2
0

This might help you

<select id="roles" required formControlName="userRole">
 <option *ngFor="let roles of URoles;let i = index;" [value]="roles._id" selected="i==0">{{roles.name}}</option>
</select>

Also no need for ng-container here.

Answer 2 - If you need attr.selected attribute to be working use the code below :

<select id="roles" required formControlName="userRole">
 <option *ngFor="let roles of URoles;let i = index;" [value]="roles._id" [attr.selected]="i == 1">{{roles.name}}</option>
</select>
swetansh kumar
  • 475
  • 7
  • 17
0

Pls try this

<select id="roles" required formControlName="userRole">
    <option *ngFor="let roles of URoles" [selected]="roles._id == 0" [value]="roles._id" >{{ roles.name }}</option>
</select>

Worked for me. Hope this will work for you.

Veena K. Suresh
  • 942
  • 5
  • 16