Add placeholder to select tag in angular2

2020-03-01 03:32发布

I have simple component that contains only form:

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 = '';
  }
}

I want to create "placeholder" for my select, however ng-model overrides selected property which cause no selected option at all. Any sugestions? I am using angular 2.0.0-alpha.48.

标签: angular
15条回答
Melony?
2楼-- · 2020-03-01 03:38

I could not get any of the above answers working for me on Chrome 60.0.3112.113. Mainly, using value="null", or value="" on the placeholder option left the option blank in the select box. In my attempts, the value needed to me the text of the placeholder for it to show up.

component:

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 here: https://plnkr.co/edit/VPj86UTw1X2NK5LLrb8W

The action button is disabled until the selected value is not equal to the default placeholder text value.

*I was getting errors using ngModel (plunker only), so I used a (change) function on the select to update the selected value.

查看更多
Melony?
3楼-- · 2020-03-01 03:39
<select class="form-control" [(ngModel)]="mySelect">
<option value="-1">Placeholder text..</option>
<!-- forloop of options heres -->
</select>

Then in your component. this.mySelect = -1;

查看更多
够拽才男人
4楼-- · 2020-03-01 03:41

May be I am somewhat late to this question

As @Thomas Watson answer does not work for angular 4 and upward so this best solution is :

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

Then in the component :

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

Note : This also works for required field validation

查看更多
手持菜刀,她持情操
5楼-- · 2020-03-01 03:44

Angular 5 Solution and with Reactive forms!

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

:)

查看更多
啃猪蹄的小仙女
6楼-- · 2020-03-01 03:45

I got this to work by doing the following:

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>

then using css ng-pristine for styling

select {
 border: 1px solid transparent;
  &.ng-pristine{
    font-style: italic;
    color: darken($white, 50%);
  }
}
查看更多
Root(大扎)
7楼-- · 2020-03-01 03:45

Below is my solution:

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>

This code will hide placeholder as soon as correct answer will be selected.

查看更多
登录 后发表回答