Add placeholder to select tag in angular2

后端 未结 15 1373
眼角桃花
眼角桃花 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: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:

    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.

提交回复
热议问题