0

Why ngModel is creating blank element in HTML - select - option? How can I get rid of this?

First code.

  <div style="text-align: center;">
    <label for="sel1">Select list (select one):</label>
    <select class="form-control" id="sel1" style="height: 3rem; width: max-content; margin-left: 33.5rem;" (change)="getSelectedUserAccess()">
      <option>suman</option>
      <option selected>rony</option>
      <option>alex</option>
    </select>
  </div>

Screenshot:

enter image description here

Second code [wrong]

  <div style="text-align: center;">
    <p>Select User : </p>
    <select [(ngModel)]="currentSelectedUser" class="form-control" id="userSelect1"
      style="height: 3rem; width: max-content; margin-left: 33.5rem;" (change)="getSelectedUserAccess()">
      <option>suman</option>
      <option selected>rony</option>
      <option>alex</option>
    </select>
  </div>

screnshot :

enter image description here

6
  • What is the value of currentSelectedUser variable in .ts file ? Commented Jul 28, 2020 at 9:16
  • @HarmandeepSinghKalsi blank, no value . It will get value when I call (change)="getSelectedUserAccess()" Commented Jul 28, 2020 at 9:25
  • initialize the ngModel in the component like this: export class Component implements OnInit { currentSelectedUser = 'rony'; or better use an array of name and initialize the ngModle with the first value of the array Commented Jul 28, 2020 at 9:27
  • @Christoph Right now, I am manually giving select option . But it will come from db, so i dont know what it will be then Commented Jul 28, 2020 at 9:28
  • 1
    @Frost and the first result from the database should be selected? Then I still would initialize it with an empty value(like you do) and set it after you get the result from the database Commented Jul 28, 2020 at 9:32

1 Answer 1

2

You need to initialize ngModel value with the value from database or 'rony'. Also maintain an array for list of users so that you can show the selectedCurrentUser as the selected user by default using [selected]="currentSelectedUser===user".

html:

    <div style="text-align: center;">
    <p>Select User : </p>
    <select [(ngModel)]="currentSelectedUser" class="form-control" id="userSelect1"
      style="height: 3rem; width: max-content; margin-left: 33.5rem;" 
      (change)="getSelectedUserAccess()">
      <option *ngFor="let user of users" [selected]="currentSelectedUser === user"> 
      {{user}}
     </option>
    </select>
  </div>

ts:

  users:Array<string>=['suman', 'alex', 'rony'];
  currentSelectedUser:string;

  constructor(private usrService:UserService){  }

  ngOnInit(){
   this.currentSelectedUser = this.usrService.getCurrentUser(); //rony
  }

  getSelectedUserAccess(){
    console.log("Current Selected User", this.currentSelectedUser)
  }
Sign up to request clarification or add additional context in comments.

Comments