【问题标题】:Angular: ngmodel creates blank select option in HTMLAngular:ngmodel 在 HTML 中创建空白选择选项
【发布时间】:2020-11-17 16:44:07
【问题描述】:

为什么ngModelHTML - select - option 中创建空白元素?我怎样才能摆脱它?

第一个代码。

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

截图:

【问题讨论】:

  • .ts 文件中 currentSelectedUser 变量的值是多少?
  • @HarmandeepSinghKalsi 空白,没有价值。当我调用 (change)="getSelectedUserAccess()" 时,它将获得价值
  • 像这样初始化组件中的ngModel:export class Component implements OnInit { currentSelectedUser = 'rony';或者更好地使用名称数组并使用数组的第一个值初始化 ngModle
  • @Christoph 现在,我手动提供选择选项。但它会来自 db,所以我不知道它会是什么
  • @Frost 并且应该选择数据库中的第一个结果?然后我仍然会用一个空值初始化它(就像你一样)并在你从数据库中得到结果后设置它

标签: javascript html css angular typescript


【解决方案1】:

您需要使用来自数据库或“rony”的值初始化 ngModel 值。还为用户列表维护一个数组,以便您可以默认使用[selected]="currentSelectedUser===user" 将 selectedCurrentUser 显示为选定用户。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 2012-01-26
    • 1970-01-01
    • 2019-01-16
    相关资源
    最近更新 更多