ngFor 生成的表单输入值 table

Form input value in an ngFor generated table

我希望能够为 table 中的任何玩家提交号码。

我正在 Angular2 中使用 *ngFor 生成 table。
对于 table 中的每个元素,我添加了一个带有输入字段的表单。

我如何提交并包含来自这些表单的输入值?

<table>
    <tr>
        <th>Name</th>
        <th>Value</th>
        <th>Bid</th>
    </tr>
    <tr *ngFor="#player of players">
        <td>{{player.name}}</td>
        <td>{{player.value | currency:'GBP':true:'4.0-0'}}</td>
        <td>
            <form role="form" (submit)="onBid($event, player)">
                <input type="number" min={{player.value}} value={{player.value}}>
                <button type="submit">Bid</button>
            </form>
        </td>
    </tr>
</table>

我一直无法从输入框中提交和检索值。
为静态表单执行此操作,我可以在其中定义 id="inputname"#inputname,然后将 inputname.value 添加到 (submit)="onBid(inputname.value)" 作品中。

我试过 adding id={{player.id}}#{{player.id}} 但不知道如何将其添加到 onBid()

如果您想 "post" 整个表单,为什么不利用 ngModel 绑定到数组或对象。

这是一个带有数组的示例:

@Component({
  selector: 'my-app',
  template: `
    <form role="form" (submit)="onBid($event, player)">
    <table>
    <tr>
      <th>Name</th>
      <th>Value</th>
      <th>Bid</th>
    </tr>
    <tr *ngFor="#player of players; #i=index">
      <td>{{player.name}}</td>
      <td>{{player.value | currency:'GBP':true:'4.0-0'}}</td>
      <td>
        <input type="number" [(ngModel)]="bids[i]"
               min="{{player.value}}" value="{{player.value}}">
      </td>
    </tr>
    </table>
    <button type="submit">Bid</button>
    </form>
  `
})
export class AppComponent {
  constructor() {
    this.players = [
      (...)
    ];
    this.bids = [];
  }

  onBid() {
    console.log(this.bids);
  }
}

还有一个对象:

@Component({
  selector: 'my-app',
  template: `
    <form role="form" (submit)="onBid($event, player)">
    <table>
    <tr>
      <th>Name</th>
      <th>Value</th>
      <th>Bid</th>
    </tr>
    <tr *ngFor="#player of players; #i=index">
      <td>{{player.name}}</td>
      <td>{{player.value | currency:'GBP':true:'4.0-0'}}</td>
      <td>
        <input type="number" [(ngModel)]="bids[player.name]"
               min="{{player.value}}" value="{{player.value}}">
      </td>
    </tr>
    </table>
    <button type="submit">Bid</button>
    </form>
  `
})
export class AppComponent {
  constructor() {
    this.players = [
      (...)
    ];
    this.bids = {};
  }

  onBid() {
    console.log(this.bids);
  }
}

看到这个 plunkr:https://plnkr.co/edit/Ox4HmliuX3ESdf8JIZgr?p=preview

working Demo

<td>
   <form role="form" (submit)="onBid($event, player, name.value)">
      <input type="number" #name  min={{player.value}} value={{player.value}}>
      <button type="submit">Bid</button>
   </form>
</td>

onBid(e,player,value) {
   player.inputValue=value; //<-----this will add new property to your existing object with input value.
   console.log(player);
}