user12504785
user12504785

Reputation:

Angular: ngmodel creates blank select option in HTML

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

Upvotes: 0

Views: 1572

Answers (1)

Pallavi
Pallavi

Reputation: 506

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)
  }

Upvotes: 2

Related Questions