【问题标题】:Angular2 : Cannot get input values of Inputs repeated by NgFor in a ngFormAngular2:无法获取 NgFor 在 ngForm 中重复的输入值
【发布时间】:2017-01-03 08:56:57
【问题描述】:

我正在尝试设置管理员用户可以设置气瓶价格的表单。一个瓶子有一个类型、一个名称和一个价格如下:

export class Bottle {

  constructor(
    public typeId: string,
    public name: string,
    public price: number
  )
  { }
}

这是显示的表单:AccountID 输入和使用 ngFor 重复的瓶子列表。

<form (ngSubmit)="onSubmit()" #bottleUpdatePriceForm="ngForm" >

    <div class="form-group">
      <label for="accountId ">Account ID : </label>
      <input type="text" class="form-control" id="accoundId" name="accountId" required [(ngModel)]="accountId">
    </div>

    <div class="form-group" *ngFor="let bottle of bottleArrayToUpdate; let i = index">
      <label for="bottlePrice ">{{bottle.name}} : </label>
      <input type="text" class="form-control" id="bottlePrice" name="bottlePrice" [ngModel]="bottleArrayToUpdate[i].price">
    </div>

    <button type="submit" class="btn btn-default">Submit</button>
  </form>

我将数据作为瓶子数组(实际上是 6 个)从另一个组件发送到我的表单,其中设置了它们的 TypeName,以及价格为空。

@Input() private bottleArrayToUpdate: Bottle[];

...

onSubmit() {
    this.submitted = true;    

    console.log(this.accountId); // => Works fine
    console.log(this.bottleArrayToUpdate); // => All the prices are still null
}

有没有办法获取瓶子重复输入的输入值,并且使用标准形式,而不是反应形式?

我也尝试使用[ngModel]="bottle.price,但我也无法访问我的值。

感谢您的帮助

【问题讨论】:

  • 另外,可能是重复的,但我在其他帖子中没有找到答案,因此我提出了问题。

标签: angular angular2-forms ngfor


【解决方案1】:

您应该使用[()] 表示法来确保双向绑定:

  <input type="text" name="bottlePrice" [(ngModel)]="bottle.price">

也不要使用id,因为这在页面中应该是唯一的,并且您在*ngFor 中使用它:)

【讨论】:

  • 天哪,我想知道为什么这行不通……难怪……我觉得错过它真的很愚蠢。非常感谢 ! (以及好的提示)
  • 我想了很多:),因为你确实在accoundId使用过它
猜你喜欢
  • 2015-04-28
  • 2016-08-22
  • 2017-08-28
  • 2018-01-18
  • 2017-12-04
  • 1970-01-01
  • 2017-10-15
  • 2017-03-11
  • 1970-01-01
相关资源
最近更新 更多