1

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

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

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

<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"#inputnameinputname.value(submit)="onBid(inputname.value)"

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

4

2 回答 2

3

工作演示

<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);
}
于 2016-04-11T07:40:24.260 回答
1

如果您想“发布”整个表单,为什么不利用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 。

于 2016-04-11T07:31:58.453 回答