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条回答
放我归山
2楼-- · 2020-03-01 03:57
<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
查看更多
狗以群分
3楼-- · 2020-03-01 04:00

This is how we I do it:

<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>
查看更多
Animai°情兽
4楼-- · 2020-03-01 04:01

I know i'm late , this is how i'm doing ,

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

ngOnInit(){
 this.initializeSelectOptions();
}

In my template ,

<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>
查看更多
登录 后发表回答