【问题标题】:Add placeholder to select tag in angular2添加占位符以在angular2中选择标签
【发布时间】:2015-12-09 16:16:43
【问题描述】:

我有一个只包含表单的简单组件:

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

我想为我的选择创建“占位符”,但是 ng-model 会覆盖 selected 属性,这会导致根本没有选择的选项。有什么建议吗?我正在使用角度 2.0.0-alpha.48。

【问题讨论】:

  • 在您的构造函数中,尝试this.model.server = 'placeholder';。这是Plunker

标签: angular


【解决方案1】:

Angular 5 解决方案和响应式表单!

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

:)

【讨论】:

  • 使用 Angular Reactive Forms 效果很好!
  • 我现在已经搜索了 1 小时。非常感谢!
  • 为了使它真正光滑,还可以添加 [hidden]=true
  • 如果 FormControl 的初始值为 null。 value 和 disabled 属性应该够用了。
  • 这里有一个错误,通过声明 value="null" 它实际上会保存一个字符串 "null"。
【解决方案2】:

这对我有用

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


我的回答基于this answerthis answer

【讨论】:

    【解决方案3】:

    以下是我在使用响应式表单时的解决方案

     <select formControlName="myctrlName">
            <option [disabled]="true" [selected]="true">Select Option</option>
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
        </select>
    

    【讨论】:

    • 最佳答案!像魅力一样工作。我想补充一点,如果您想在选择字段中显示文本“选择选项”而不单击它,则必须添加value="",否则直到您单击它才会显示。
    【解决方案4】:

    我通过执行以下操作使其工作:

    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>
    

    然后使用 css ng-pristine 进行样式化

    select {
     border: 1px solid transparent;
      &.ng-pristine{
        font-style: italic;
        color: darken($white, 50%);
      }
    }
    

    【讨论】:

    • 密钥是[selected]="!model.metrics.type"
    • 这很好用,虽然我稍微改变了它,因为我使用的是 formGroup 而不是 ngModel:[selected]="selectControl.pristine"
    【解决方案5】:
    <select class="form-control" [(ngModel)]="mySelect">
    <option value="-1">Placeholder text..</option>
    <!-- forloop of options heres -->
    </select>
    

    然后在您的组件中。 this.mySelect = -1;

    【讨论】:

    • 投票作为我接受的答案。这是最有说服力的解决方案——处理-1 比区分0null (等等)要容易得多。
    • 这适用于 select 中的 [(ngModel)]。稍作修改
    【解决方案6】:

    可能我这个问题有点晚了

    由于@Thomas Watson 的回答不适用于 angular 4 及以上,所以这个最佳解决方案是:

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

    然后在组件中:

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

    注意:这也适用于必填字段验证

    【讨论】:

      【解决方案7】:

      这就是我的做法:

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

      【讨论】:

        【解决方案8】:
        <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
        

        【讨论】:

          【解决方案9】:

          这在 Angular 5 中使用响应式表单对我有用,下拉列表是 FormControl。关键是:

          • 在TypeScript中将下拉控件的初始化为[null]
          • 在占位符选项上使用[ngValue]="null"

          (或者您可以使用0 或负数代替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>
          

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

          【讨论】:

            【解决方案10】:

            @Thomas 上面的回答让我快到了,但 [selected] is ignored when using [(ngModel)]。 @Baconbeastnz 的回答可行,但无法解决 form validation

            这是我将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>
            

            注意:出于表单验证的目的,我特意选择了 selectedState.code 而不是 selectedState
            注意2:我选择禁用占位符“状态”选项。 注意 2:这可能是一个 hack,但 minlength 用于表单验证目的,并检查代码是否最小长度为 2

            stateList.ts

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

            注意:我选择了第一个条目作为占位符,如下图

            form.component.ts

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

            注意:起初,我只是简单地分配了 selectedState = this.stateList[0],但它所做的是通过引用而不是值来分配。我需要Object.assign 来复制 stateList 值的第一个条目。否则,下拉列表中任何其他值的选择都将执行运算符this.stateList[0] = state.code;

            【讨论】:

            • 另一个提示,如果要隐藏选项,请使用 [hidden] 属性。 [disabled] 和 [hidden] 是在 SELECT 字段上进行提示的好方法。
            【解决方案11】:
            <select name="selectName" [ngModel]="someModelObject">
              <option [ngValue]="undefined" disabled hidden>Select item</option>
              <option *ngFor="let item of items" [ngValue]="item">item</option>
            </select>
            

            为我工作。

            【讨论】:

              【解决方案12】:

              以下是我的解决方案:

              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>
              

              一旦选择正确答案,此代码将隐藏占位符。

              【讨论】:

                【解决方案13】:
                [ngValue]="myObject.myKey"
                

                是你想要的。

                【讨论】:

                  【解决方案14】:

                  我知道我迟到了,我就是这样,

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

                  在我的模板中,

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

                  【讨论】:

                    【解决方案15】:

                    我无法在 Chrome 60.0.3112.113 上获得任何上述答案。主要是在占位符选项上使用value="null"value="" 将选择框中的选项留空。在我的尝试中,该值需要占位符的文本才能显示出来。

                    组件:

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

                    在所选值不等于默认占位符文本值之前,操作按钮被禁用。

                    *我在使用 ngModel(仅限 plunker)时遇到错误,因此我在 select 上使用了 (change) 函数来更新所选值。

                    【讨论】:

                      猜你喜欢
                      • 2012-01-12
                      • 1970-01-01
                      • 2013-07-10
                      • 1970-01-01
                      • 2020-12-27
                      • 1970-01-01
                      • 2021-01-25
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多