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

1
  • let me know it worked for you or not Commented May 9, 2018 at 17:29

2 Answers 2

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 = '' 
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.