简体   繁体   English

Angular:ngmodel 在 HTML 中创建空白 select 选项

[英]Angular: ngmodel creates blank select option in HTML

Why ngModel is creating blank element in HTML - select - option ?为什么ngModelHTML - select -选项中创建空白元素? 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:截屏:

在此处输入图像描述

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:截图:

在此处输入图像描述

You need to initialize ngModel value with the value from database or 'rony'.您需要使用来自数据库或“rony”的值初始化 ngModel 值。 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" .还为用户列表维护一个数组,以便您可以默认使用[selected]="currentSelectedUser===user"将 selectedCurrentUser 显示为选定用户。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM