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条回答
Root(大扎)
2楼-- · 2020-03-01 03:48

Below is my solution while using Reactive forms

 <select formControlName="myctrlName">
        <option [disabled]="true" [selected]="true">Select Option</option>
        <option>Option 1</option>
        <option>Option 2</option>
        <option>Option 3</option>
    </select>
查看更多
男人必须洒脱
3楼-- · 2020-03-01 03:50
[ngValue]="myObject.myKey"

is what you want.

查看更多
爷的心禁止访问
4楼-- · 2020-03-01 03:52

This worked for me in Angular 5 using reactive forms, for a dropdown that's a FormControl. The key is:

  • initialise value of the dropdown control to [null] in the TypeScript
  • use [ngValue]="null" on the placeholder option

(or you could use 0 or a negative number instead of 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>

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

查看更多
太酷不给撩
5楼-- · 2020-03-01 03:53
<select name="selectName" [ngModel]="someModelObject">
  <option [ngValue]="undefined" disabled hidden>Select item</option>
  <option *ngFor="let item of items" [ngValue]="item">item</option>
</select>

Works for me.

查看更多
一纸荒年 Trace。
6楼-- · 2020-03-01 03:54

this work for me

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


my answer is based on this answer and this answer

查看更多
劫难
7楼-- · 2020-03-01 03:55

@Thomas's answer above got me almost there, but [selected] is ignored when using [(ngModel)]. @Baconbeastnz's answer can work, but it fails to address form validation.

Here is an answer that I got from piecing together answers from 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>

Note: I purposely chose selectedState.code instead of selectedState for form validation purposes.
Note2: I chose to disable the placeholder "State" option. Note2: This may be a hack, but minlength is used for form validation purposes, and checks if the code is a minimum length of 2

stateList.ts

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

Note: I chose the first entry as the placeholder, as shown below in

form.component.ts

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

Note: At first, I simply assigned selectedState = this.stateList[0], but what that does is assign by reference, not value. I needed Object.assign to make a copy of the first entry of the stateList value. Otherwise, any selection of other values in the dropdown will perform the operator this.stateList[0] = state.code;

查看更多
登录 后发表回答