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

时间:2018-08-21 13:08:02

标签: javascript angular typescript angular-forms

我正在使用角度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

5 个答案:

答案 0 :(得分:3)

您需要在选择框中设置一个值,如下所示:

viewDidLoad

将使其正常工作。

答案 1 :(得分:1)

添加[value]=""

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

,如果您想隐藏禁用选项,请添加hidden属性

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

答案 2 :(得分:1)

ReactiveForms

我几乎建议使用ReactiveForms。这样,您将获得更简洁的代码以及更强大的选项。

首先将ReactiveForms导入您的app.module

import {FormsModule, ReactiveFormsModule} from '@angular/forms';
...
   imports: [
      ...
      ReactiveFormsModule
      ...
   ]

然后在您的控制器中:

myForm: FormGroup;
constructor(private fb: FormBuilder){
    this.myForm = this.fb.group({
          username: null
      })
}

在您的模板中:

<form [formGroup]="myForm">
   <select formControlName="username" placeholder="Select Username">
        <option disabled selected>Select User Name</option>
        <option *ngFor="let user of userList" [value]="user.uid">{{user.name }}</option>
  </select>

答案 3 :(得分:1)

该解决方案可以在以下找到 以下是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';
}

stackblitz

答案 4 :(得分:-2)

使用棱角材质而不是select和option。 例如:

   <mat-form-field>
      <mat-select placeholder="Select User Name">
        <mat-option *ngFor="let user of userList" [value]="user.uid">
          {{food.viewValue}}
        </mat-option>
      </mat-select>
    </mat-form-field>

此处有更多详细信息:https://material.angular.io/components/select/overview