1

I am trying to set the first option as a default value,but it doesn't work , do you have any solution ?

<select   class="form-control" name="user" id="user" required [(ngModel)]="model.userSelected">
         <option selected>-- SELECT USER-- </option>
         <option *ngFor="let user of users" [ngValue]="user">{{user.name}}</option>
</select>

thanks in advance. Andrea

Mike Aguilar
  • 348
  • 2
  • 3
  • 14
Gelso77
  • 1,763
  • 6
  • 30
  • 47

2 Answers2

1

Use like this:

<select class="form-control" name="user" id="user" required [(ngModel)]="model.userSelected"> <option value=''>-- SELECT USER-- </option> <option *ngFor="let user of users" [ngValue]="user">{{user.name}}</option>

And then initialize model.userSelected as an empty string:

model.userSelected = '' 
Prachi
  • 3,478
  • 17
  • 34
0

you must need to assign value to model.userSelected as you are binding it with the select control. you are not passing anything in current code of yours that why its not selecting any element.

try like this , create default user with id -1 and bind it.

component.ts

ngOnInit() {
//pull add data 
model.userSelected = {name:'', id=-1} as User;
}

html

--do not bind full object user as value , bind id of object like as done below

<select   class="form-control" name="user" id="user" required
                           [(ngModel)]="model.userSelected.id">
         <option [ngValue]='-1'>-- SELECT USER-- </option>
         <option *ngFor="let user of users" [ngValue]="user.id">{{user.name}}</option>
</select>

or

just push default element at fist in array of users, after you get all users from you call to server

    //push default element in array of user 
    user.unshift({name:'-- SELECT USER--', id=-1} as User);

 ngOnInit() {
    //pull add data 
    model.userSelected = {name:'', id=-1} as User;
    }

then

<select   class="form-control" name="user" id="user" required
                           [(ngModel)]="model.userSelected.id">
         <option *ngFor="let user of users" [ngValue]="user.id">{{user.name}}</option>
</select>
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263