首页 文章

将选择元素绑定到Angular中的对象

提问于
浏览
273

我是Angular的新手,并试图通过新的做事方式加快速度 .

我想将一个select元素绑定到一个对象列表 - 这很容易:

@Component({
   selector: 'myApp',
   template: `<h1>My Application</h1>
              <select [(ngModel)]="selectedValue">
                 <option *ngFor="#c of countries" value="c.id">{{c.name}}</option>
              </select>`
})
export class AppComponent{
    countries = [
       {id: 1, name: "United States"},
       {id: 2, name: "Australia"}
       {id: 3, name: "Canada"}
       {id: 4, name: "Brazil"}
       {id: 5, name: "England"}
     ];
    selectedValue = null;
}

在这种情况下,看起来selectedValue将是一个数字 - 所选项目的ID .

但是,我实际上想要绑定到country对象本身,以便selectedValue是对象而不仅仅是id . 我尝试改变选项的值,如下所示:

<option *ngFor="#c of countries" value="c">{{c.name}}</option>

但这似乎不起作用 . 它似乎在我的selectedValue中放置了一个对象 - 但不是我期望的对象 . 你可以see this in my Plunker example .

我也尝试绑定到change事件,以便我可以根据所选的id自己设置对象;但是,看起来更改事件在绑定的ngModel更新之前触发 - 这意味着我无法访问此时新选择的值 .

是否有一种干净的方法将选择元素绑定到具有Angular 2的对象?

9 回答

  • 4
    <h1>My Application</h1>
    <select [(ngModel)]="selectedValue">
      <option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
    </select>
    

    StackBlitz example

    注意:您可以使用 [ngValue]="c" 而不是 [ngValue]="c.id" ,其中c是完整的国家/地区对象 .

    [value]="..." 仅支持字符串值
    [ngValue]="..." 支持任何类型

    update

    如果 value 是一个对象,则预选实例需要与其中一个值相同 .

    另请参阅最近添加的自定义比较https://github.com/angular/angular/issues/13268 available since 4.0.0-beta.7

    <select [compareWith]="compareFn" ...
    

    如果您想在 compareFn 内访问 this ,请注意 .

    compareFn = this._compareFn.bind(this);
    
    // or 
    // compareFn = (a, b) => this._compareFn(a, b);
    
    _compareFn(a, b) {
       // Handle compare logic (eg check if unique ids are the same)
       return a.id === b.id;
    }
    
  • 5

    这有助于:

    <select [(ngModel)]="selectedValue">
          <option *ngFor="#c of countries" [value]="c.id">{{c.name}}</option>
    </select>
    
  • 518

    您也可以这样做,而无需在 <select> 标签中使用 [(ngModel)]

    在ts文件中声明一个变量

    toStr = JSON.stringify;

    并在你的模板中执行此操作

    <option *ngFor="let v of values;" [value]="toStr(v)">
          {{v}}
     </option>
    

    然后使用

    let value=JSON.parse(event.target.value)
    

    将字符串解析回有效的JavaScript对象

  • 13

    您可以使用功能选择ID

    <option *ngFor="#c of countries" (change)="onchange(c.id)">{{c.name}}</option>
    
  • 3

    它对我有用:

    Template HTML:

    我在 select 添加了 (ngModelChange)="selectChange($event)" .

    <div>
      <label for="myListOptions">My List Options</label>
      <select (ngModelChange)="selectChange($event)" [(ngModel)]=model.myListOptions.id >
        <option *ngFor="let oneOption of listOptions" [ngValue]="oneOption.id">{{oneOption.name}}</option>
      </select>
    </div>
    

    On component.ts:

    listOptions = [
        { id: 0, name: "Perfect" },
        { id: 1, name: "Low" },
        { id: 2, name: "Minor" },
        { id: 3, name: "High" },
      ];
    

    An you need add to component.ts this function:

    selectChange( $event) {
        //In my case $event come with a id value
        this.model.myListOptions = this.listOptions[$event];
      }
    

    注意:我尝试使用 [select]="oneOption.id==model.myListOptions.id" 并且无法正常工作 .

    ============= Another ways can be: =========

    Template HTML:

    我在 select 添加了 [compareWith]="compareByOptionId .

    <div>
      <label for="myListOptions">My List Options</label>
      <select [(ngModel)]=model.myListOptions [compareWith]="compareByOptionId">
        <option *ngFor="let oneOption of listOptions" [ngValue]="oneOption">{{oneOption.name}}</option>
      </select>
    </div>
    

    On component.ts:

    listOptions = [
        { id: 0, name: "Perfect" },
        { id: 1, name: "Low" },
        { id: 2, name: "Minor" },
        { id: 3, name: "High" },
      ];
    

    An you need add to component.ts this function:

    /* Return true or false if it is the selected */
     compareByOptionId(idFist, idSecond) {
        return idFist && idSecond && idFist.id == idSecond.id;
     }
    
  • 30

    对我这样工作,你可以控制 event.target.value .

    <select (change) = "ChangeValue($event)" (ngModel)="opt">   
        <option *ngFor=" let opt of titleArr" [value]="opt"></option>
    </select>
    
  • 1

    万一有人希望使用Reactive Forms做同样的事情:

    <form [formGroup]="form">
      <select formControlName="country">
        <option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
      </select>
      <p>Selected Country: {{country?.name}}</p>
    </form>
    

    检查工作示例here

  • 5

    此外,如果给定解决方案中的任何其他内容都不起作用,请检查是否在“AppModule”中导入了“FormsModule”,这对我来说是一个关键 .

  • 2

    您还可以通过在函数中传递所选值,在click()的帮助下获得选定的值

    <md-select placeholder="Select Categorie"  
        name="Select Categorie" >
      <md-option *ngFor="let list of categ" [value]="list.value" (click)="sub_cat(list.category_id)" >
        {{ list.category }}
      </md-option>
    </md-select>
    

相关问题