Add placeholder to select tag in angular2

后端 未结 15 1368
眼角桃花
眼角桃花 2021-01-03 19:54

I have simple component that contains only form:

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


@Component({
  selector: \'test-com         


        
相关标签:
15条回答
  • 2021-01-03 20:22

    this work for me

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


    my answer is based on this answer and this answer

    0 讨论(0)
  • 2021-01-03 20:25
    <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.

    0 讨论(0)
  • 2021-01-03 20:28

    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

    0 讨论(0)
  • 2021-01-03 20:29

    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.

    0 讨论(0)
  • 2021-01-03 20:30

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

    0 讨论(0)
  • 2021-01-03 20:31

    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>
    
    0 讨论(0)
提交回复
热议问题