angular - 访问 FormArray 中的对象属性并更新 Angular 4 中的值

标签 angular typescript angular-reactive-forms formarray

我想从表单访问对象属性和绑定(bind)值。到目前为止,我尝试了不同的选择但没有成功。这是我目前所拥有的,我简化了下面的代码:

表单组:

this.form = this.fb.group({
  ingredients: new FormArray([this.fb.group({name: 'Pasta', price: ''})])
})

查看代码:

<div formArrayName="ingredients">
  <ion-item *ngFor="let ingredient of form['controls'].ingredients['controls']; let i = index" padding-bottom>
    <div [formGroupName]="i">
        <ion-input formControlName="price" type="number"></ion-input>
    </div>
  </ion-item>
</div>

上面的代码是为了这个问题而简化的,场景是不同的,但最后我想更新对象内的价格值。在进行研究时,我已经看到了很多方法,但似乎没有一种对我有用。

最佳答案

试试这个:-

  <form [formGroup]="form">
  <div formArrayName="ingredients">
    <div *ngFor="let ingredient of form['controls'].ingredients['controls']; let i = index" [formGroupName]="i">
    <input formControlName="price" type="number"/>
    </div>
    </div>
  </form>

和 ts:-

form: FormGroup;

  constructor(builder: FormBuilder) {
    this.form = builder.group({
      ingredients: new FormArray([
        builder.group({
            name: 'Pasta',
            price: '',
        })
      ]);
    })
  }

请检查这个 plunker 的解决方案。 http://plnkr.co/edit/it3VW8wvYfYmk2Ox6M60?p=preview

关于angular - 访问 FormArray 中的对象属性并更新 Angular 4 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47298236/

相关文章:

javascript - Angular2 ng2-auto-complete 实现问题

node.js - 创建 ionic 项目失败?

javascript - Promise.all 在调用具有不同返回类型的多个异步函数时抛出类型错误

Angular 11 - 验证 for 循环中生成的子表单

javascript - 在 angular2/typescript 中使用 jointjs

javascript - 第一次学习 Angular - 版本 2 还是版本 4?

javascript - jQuery promise 出现意外的 "then"调用顺序

javascript - 使用 typescript 在 angular2 中进行加法运算

angular - 响应式(Reactive)表单元素在 Dragula 的拖动幽灵中显示不同的 <select> 值

angular6 - 为什么 Angular ReactiveForms FormArray 会抛出错误 "TypeError: Cannot read property ' updateOn' of null”