Angular 2 ngModel和带select元素的索引

时间:2017-01-05 23:44:55

标签: angular ngfor angular2-ngmodel

我有像这样的循环

<template ngFor let-game [ngForOf]="(games)" let-index="index">
    <tr>
        <td>
            <select [(ngModel)]="selectedPrice" class="form-control" name="">
                <option *ngFor="let price of prices">{{price}}</option>
            </select>
        </td>
        <td>
    </tr>
</template>

显然,更改一个元素的价格会改变所有其他元素的价格。

这是我改变一个下降时的意思的分支,它会改变另一个。 https://plnkr.co/edit/LVViSdlgmY56RnO8mAU4?p=preview

我的问题是:有没有办法利用模板元素中的索引只为生成的每个元素绑定一个selectedPrice?因此,当我更改一个下拉值的值时,它不会为所有其他值更改它们

我尝试过某些语法,如[(ngModel)] =“selectedPrice [index]”,当我选择价格时,它没有做我想要的意思,selectedPrice [index]实际上并不包含值。我还有其他几种方法可行,但它们很黑。

2 个答案:

答案 0 :(得分:4)

https://plnkr.co/edit/nOQ4ve9ee2A1TZjvrQBS?p=preview

&#13;
&#13;
//our root app component
import {Component, NgModule} from '@angular/core'
import {FormsModule} from '@angular/forms'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
      <tr *ngFor="let game of games; let i='index'">
        <td>
          {{game.name}} {{i}} {{game.price}}
        </td>
        <td>
            <select [(ngModel)]="games[i].price" class="form-control">
                <option *ngFor="let price of prices">{{price}}</option>
            </select>
        </td>
    </tr>
  `,
})
export class App {
  constructor() {}
  
  prices = ['40$', '30$', '20$'];
  games = [{name:'ge64'}, {name:'SM64'}];
  
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试以下代码。 selectedPrice变量现在包含选定的值。

@Component({
  selector: 'my-app',
  template: `
      <tr>
        <td>
          <select [(ngModel)]="selectedPrice" class="form-control" name="" (change)="select()">
            <option *ngFor="let price of prices">{{price}}</option>
          </select>
        </td>
      </tr>
    <input id="result">
  `,
})

export class App {
  constructor() {}

  prices = ['40$', '30$', '20$']

  select(){
     document.getElementById('result').value = this.selectedPrice;
     console.log(this.selectedPrice);
  }
}

<强> Plunker code