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

  • What is the value of currentSelectedUser variable in .ts file ? – Harmandeep Singh Kalsi Jul 28 '20 at 09:16
  • @HarmandeepSinghKalsi blank, no value . It will get value when I call (change)="getSelectedUserAccess()" –  Jul 28 '20 at 09: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 – Christoph Jul 28 '20 at 09: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 –  Jul 28 '20 at 09: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 – Christoph Jul 28 '20 at 09:32
  • @Christoph Hmm, that's a possible solution –  Jul 28 '20 at 09:33

1 Answers1

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)
  }
Pallavi
  • 496
  • 5
  • 12