Angular 2,设置默认值以选择选项

2024-01-19

我尝试为选项添加默认值。它就像一种占位符,我使用这个方法 https://stackoverflow.com/questions/5805059/how-do-i-make-a-placeholder-for-a-select-box去做吧。 在纯 HTML 中它可以工作,但是如果我尝试使用*ngFor角度 2 属性,它不选择任何内容。

这是我在纯 HTML 中使用的代码:

  <select name="select-html" id="select-html">
    <option value="0" selected disabled>Select Language</option>
    <option value="1">HTML</option>
    <option value="2">PHP</option>
    <option value="3">Javascript</option>
  </select>

并使用 Angular 模板:

 <select name="select" id="select" [(ngModel)]="selectLanguage">
    <option *ngFor="let item of selectOption" 
      [selected]="item.value==0" 
      [disabled]="item.value==0">{{item.label}}</option>
  </select>

班级是

import {Component} from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-form-select',
  templateUrl: 'default.component.html'
})
export class DefaultComponent {
  private selectOption: any;
  constructor() {
    this.selectOption = [
      {
        id: 1,
        label: "Select Language",
        value: 0
      }, {
        id: 2,
        label: "HTML 5",
        value: 1
      }, {
        id: 3,
        label: "PHP",
        value: 2
      }, {
        id: 4,
        label: "Javascript",
        value: 3
      }
    ]
  }
}

I want Select Language被选为默认值。它已禁用但未选择。

如何选择它作为默认值?

实例 http://plnkr.co/edit/fuMlp7XE8tDlDYLoOfni?p=preview


update

4.0.0-beta.6 https://github.com/angular/angular/compare/4.0.0-beta.5...4.0.0-beta.6 added compareWith

<select [compareWith]="compareFn"  [(ngModel)]="selectedCountries">
    <option *ngFor="let country of countries" [ngValue]="country">
        {{country.name}}
    </option>
</select>

compareFn(c1: Country, c2: Country): boolean {
   return c1 && c2 ? c1.id === c2.id : c1 === c2;
} 

这样实例就分配给了selectedCountries不需要是相同的对象,但可以传递自定义比较函数,例如能够将具有相同属性值的不同对象实例进行匹配。

original

如果你想使用一个对象作为值,你需要使用[ngValue]在选项元素上。

  <select name="select" id="select" [(ngModel)]="selectLanguage">
    <option *ngFor="let item of selectOption" [ngValue]="item"
      [disabled]="item.value==0">{{item.label}}</option>
  </select>

When selectLanguage已分配选项值[(ngModel)]="..."这是否会成为默认选择的一项:

import {Component} from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-form-select',
  templateUrl: 'default.component.html'
})
export class DefaultComponent {
  private selectOption: any;
  constructor() {
    this.selectOption = [
      {
        id: 1,
        label: "Select Language",
        value: 0
      }, {
        id: 2,
        label: "HTML 5",
        value: 1
      }, {
        id: 3,
        label: "PHP",
        value: 2
      }, {
        id: 4,
        label: "Javascript",
        value: 3
      }
    ];
    this.selectLanguage = this.selectOption[0];
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2,设置默认值以选择选项 的相关文章

随机推荐