首页 文章

Angular 2 ngModel和带select元素的索引

提问于
浏览
0

我有一个像这样的循环

<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]实际上并不包含值 . 我有其他一些方法可行,但他们是hacky .

2 回答

  • 1

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

    //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 {}
    
  • 4

    请尝试以下代码 . 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

相关问题