选择框不首先显示所选选项

新手上路,请多包涵

我使用的是 angular 6,我无法在选择框中将所选选项显示为默认值,

HTML 包括,

 <select class="form-control selectBox" name="username" #username="ngModel" required ngModel>
<option disabled selected>Select User Name</option>
<option *ngFor="let user of userList" [value]="user.uid">{{user.name }}</option>
</select>

TS:

 import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  userList: any = [
    {
      "name" : "Test User"
    },
    {
      "name" : "Hello World"
    },
    {
      "name" : "User Three"
    }
  ]
}

它在选择框中默认显示空值。

我如何在该行的选择框中将所选选项显示为默认选项?

 <option disabled selected>Select User Name</option>

Stackblitz: https ://stackblitz.com/edit/angular-wfjmlm

原文由 Maniraj Murugan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 262
2 个回答

您需要像这样在选择框中设置一个值:

 <option disabled selected value="">Select User Name</option>

会让它工作。

原文由 Sanoj_V 发布,翻译遵循 CC BY-SA 4.0 许可协议

解决方案可以在下面找到,下面是 html

 <select class="form-control selectBox" name="username" [(ngModel)]="selected" required>
 <option disabled selected>Select User Name</option>
 <option *ngFor="let user of userList" >{{user.name }}</option>
</select>
<hr>   {{selected}}

以下是控制器

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  userList: any = [
    {
      "name": "Test User"
    },
    {
      "name": "Hello World"
    },
    {
      "name": "User Three"
    }
  ];
  selected = 'Select User Name';
}

堆栈闪电战

原文由 Krishna Kanth 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题