角度:ngmodel在HTML中创建空白选择选项 [英] Angular: ngmodel creates blank select option in HTML

查看:61
本文介绍了角度:ngmodel在HTML中创建空白选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 ngModel HTML -选择-选项中创建空白元素?我该如何摆脱呢?

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

第一个代码.

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

屏幕截图:

第二个代码[错误]

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

screnshot :

推荐答案

您需要使用数据库或'rony'中的值来初始化ngModel值.还要维护一个用于用户列表的数组,以便默认情况下您可以使用 [selected] =" currentSelectedUser === user" 将selectedCurrentUser显示为所选用户.

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

这篇关于角度:ngmodel在HTML中创建空白选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆