添加占位符以在angular2中选择标记

时间:2015-12-09 16:16:43

标签: angular

我有一个只包含表单的简单组件:

import {Component, FORM_DIRECTIVES, NgFor} from 'angular2/angular2';


@Component({
  selector: 'test-component',
  directives: [FORM_DIRECTIVES, NgFor],
  template: `
    <form class="form-inline" (ng-submit)="onSubmit()" #form="form">
      <div class="form-group">
        <select class="form-control" 
          [(ng-model)]="model.server" 
          ng-control="server" 
          #server="form" 
          required>
          <option selected hidden>placeholder</option>
          <option *ng-for="#server of servers" 
            [value]="server">{{ server | uppercase }}
          </option>
        </select>
      </div>
      <div class="form-group">
        <input class="btn btn-primary" type="submit" value="Load"
          [disabled]="!form.form.valid">
      </div>
    </form>
  `
})
export class TestComponent {
  public model: Model = new Model();
  public servers: string[] = ['a', 'b', 'c'];

  onSubmit(): void {
    // Complicated logic.

    // Reset form.
    this.model.reset();
  }
}

class Model {
  constructor(
    public server: string = ''
  ) { }

  reset(): void {
    this.server = '';
  }
}

我想为我的选择创建“占位符”,但ng-model会覆盖所选属性,导致根本没有选择选项。任何sugestions?我正在使用角度2.0.0-alpha.48。

15 个答案:

答案 0 :(得分:22)

我通过以下方式让这个工作:

enter code here

<div class="form-group">
  <label for="metricsType">metrics type</label>
  <select id="metricsType" class="form-control" required [(ngModel)] ="model.metrics.type">
     <option value="" disabled="true" [selected]="!model.metrics.type">--please select--</option>
     <option *ngFor="let item of metricTypes" [value]="item.value">{{item.label}}</option>
  </select>
 </div>

然后使用css ng-pristine进行样式设计

select {
 border: 1px solid transparent;
  &.ng-pristine{
    font-style: italic;
    color: darken($white, 50%);
  }
}

答案 1 :(得分:14)

<select class="form-control" [(ngModel)]="mySelect">
<option value="-1">Placeholder text..</option>
<!-- forloop of options heres -->
</select>

然后在你的组件中。 this.mySelect = -1;

答案 2 :(得分:14)

Angular 5解决方案和反应形式!

<option value="null" disabled="true" [selected]="true">Placeholder text..</option>

:)

答案 3 :(得分:8)

这项工作对我而言

<option [ngValue]="undefined" hidden selected> please select </option>


我的答案基于this answerthis answer

答案 4 :(得分:4)

我们就是这样做的:

<select class="form-control" name="selectedSignierer" #selectedSignierer="ngModel" [(ngModel)]="suisseIdDetail.selectedSigniererBenutzerId" required>
  <option value="null" disabled selected>Select your option</option>
  <option *ngFor="let item of signiererCatalog.entries;" value="{{ item.id }}" >{{ item.value }}</option>
</select>
<div *ngIf="fb.submitted && showSignDefinition === true && !selectedSignierer.valid" class="validation-error">{{ 'ERROR_FIELD_REQUIRED' | translate:lang }}</div>

答案 5 :(得分:3)

以下是使用Reactive表单时的解决方案

 <select formControlName="myctrlName">
        <option [disabled]="true" [selected]="true">Select Option</option>
        <option>Option 1</option>
        <option>Option 2</option>
        <option>Option 3</option>
    </select>

答案 6 :(得分:2)

@ Thomas上面的回答让我几乎到了那里,但[selected] is ignored when using [(ngModel)]。 @ Baconbeastnz的答案可行,但未能解决form validation

以下是我从around the internet拼凑答案时得到的答案。

form.html

<select name="stateId" class="state" [(ngModel)]="selectedState.code" required minlength="2">
    <option *ngFor="let state of stateList" [ngValue]="state.code" [disabled]="! state.code">{{state.name}}</option>
</select>

注意:我故意选择selectedState.code代替selectedState进行表单验证 注2:我选择禁用占位符“State”选项。 注意2:这可能是一个黑客,但minlength用于表单验证,并检查代码是否最小长度为2

stateList.ts

export const STATELIST : US_States[] =[
    {
        "name":"State",
        "code":""
    },
    {
        "name": "Alabama",
        "code": "AL"
    },
    {
        "name": "Alaska",
        "code": "AK"
    }, ...
];

注意:我选择第一个条目作为占位符,如下面的

所示

form.component.ts

stateList:US_States[] = STATELIST;
public selectedState: US_States = Object.assign({}, this.stateList[0]);

注意:首先,我只是分配了selectedState = this.stateList [0],但它的作用是通过引用分配,而不是值。我需要Object.assign来复制stateList值的第一个条目。否则,下拉列表中任何其他值的选择都将执行运算符this.stateList[0] = state.code;

答案 7 :(得分:2)

可能我对这个问题迟到了

由于@Thomas Watson的回答不适用于角4和向上,所以这个最佳解决方案是:

<div class="col-md-4 mb-3">
      <label for="gender">Gender</label>
      <select class="custom-select" name="gender" id="gender" #gender ="ngModel" [(ngModel)]="employee.gender" required>
                <option [ngValue]="null">Select Gender</option>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
       </select>
       <div class="text-danger" *ngIf="gender.invalid && gender.touched">Gender is required</div>
 </div>

然后在组件中:

ngOnInit(): void {
    this.employee = new Employee();
    this.employee.gender = null;
}

注意:这也适用于必填字段验证

答案 8 :(得分:1)

以下是我的解决方案:

export default class AppComponent {
  cityId: number = null
  ...
}
<select #chooceCity="ngModel" class="form-control" name="city [(ngModel)]="cityId" required>
  <option *ngIf="chooceCity.untouched || chooceCity.invalid" value="null" disabled selected>Choose city</option>
  <option *ngFor="let city of cities" [value]="city.id">{{city.name}}</option>
</select>

一旦选择了正确答案,此代码将隐藏占位符。

答案 9 :(得分:1)

[ngValue]="myObject.myKey"

是你想要的。

答案 10 :(得分:1)

我知道我迟到了,这就是我的工作方式,

initializeSelectOptions(){
 this.optionList = ['..' , '..' , '..'
  ];
 this.optionList.unshift('Select Options')
}

ngOnInit(){
 this.initializeSelectOptions();
}

在我的模板中,

<select class='select-option' required [(ngModel)]='optionSelected' (ngModelChange)='optionChanged($event)'>
    <option class='option' *ngFor='let option of optionList' [value]="option " [disabled]="option === 'Select Options'">{{option}}</option>
</select>

答案 11 :(得分:1)

<select name="selectName" [ngModel]="someModelObject">
  <option [ngValue]="undefined" disabled hidden>Select item</option>
  <option *ngFor="let item of items" [ngValue]="item">item</option>
</select>

适合我。

答案 12 :(得分:0)

我无法在Chrome 60.0.3112.113上获得上述任何答案。主要是,在占位符选项上使用value="null"value=""会在选择框中将选项留空。在我的尝试中,我需要的值是占位符的文本,以便显示它。

成分:

import {Component, NgModule, VERSION, OnInit } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  templateUrl: 'app.html',
  providers: [App]
})
export class App {
  selectPlaceholder = '--select--';
  serverName: string = '';
  servers: Array = [
    {id: 1, name: 'Server 1'},
    {id: 2, name: 'Server 2'},
    {id: 3, name: 'Server 3'}
    ]
  constructor() { }

  ngOnInit() {
    this.serverName = this.selectPlaceholder;
  }

  updateServer(selection) {
    this.serverName = selection;
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

HTML:

<div class="form-group">
  <label for="name">Server Name</label>
  <select
    (change)="updateServer(selection.value)"
    type="text"
    id="name"
    name="serverName"
    class="form-control"
    #selection>
    <option
      value="{{ selectPlaceholder }}"
      selected="true"
      disabled
      hidden>{{ selectPlaceholder }}</option>
    <option 
      *ngFor="let server of servers"
      value="{{ server.name }}">{{ server.name }}</option>
  </select>
</div>
<button
  class="btn btn-primary"
  [disabled]="serverName === selectPlaceholder">Update Server
</button>

此处的Plunker:https://plnkr.co/edit/VPj86UTw1X2NK5LLrb8W

操作按钮被禁用,直到所选值不等于默认占位符文本值。

*我使用ngModel(仅限plunker)收到错误,因此我在select上使用了(change)函数来更新所选值。

答案 13 :(得分:0)

这在Angular 5中使用反应形式对我有用,下拉列表为FormControl。关键是:

    将下拉控件的
  • 初始化 value 到TypeScript中的[null]
  • 在占位符选项上使用[ngValue]="null"

(或者您可以使用0或负数代替null

.ts

this.myReactiveForm = this.formBuilder.group({
  myDropdown: [null]
})

html

    <form [formGroup]="myReactiveForm ">
      <div class="form-group">
        <select formControlName="myDropdown" class="form-control" (change)="doSomething($event.target.value))">
            // DO THIS:
            <option [ngValue]="null" disabled>Please Select Option</option>
            <option *ngFor="let myItem of myCollection" [value]="myItem.id">{{ myItem.label }}</option>
        </select>
      </div>  
    </form>

来自https://netbasal.com/angular-quick-tip-how-to-show-a-placeholder-in-select-control-bab688f98b98

答案 14 :(得分:0)

<select class = "form-control"name="searchByRegion" [(ngModel)] = searchByRegion>
    <option [ngValue]="undefined" disabled>searchByRegion</option>
    <option >All</option>
    <option >Asia</option>
    <option >Europe</option>
    <option >Africa</option>
    <option >Australia</option>
</select>

this [ngValue]="undefined" is very important in 2nd line