Angular 2:从FormArray访问数据

时间:2016-11-17 05:03:14

标签: angular typescript angular2-forms

我已准备好使用angular2 / forms提供的ReactiveForms。此表单有一个表单数组产品:

this.checkoutFormGroup = this.fb.group({
            selectedNominee: ['', Validators.required],
            selectedBank: ['', Validators.required],
            products: productFormGroupArray
        });

productFormGroupArray是一个FormGroup Objects数组。我使用以下方法获取控件,即FormArray对象:

this.checkoutFormGroup.get('products')

我正在尝试将索引为i的products数组中的元素。如何在不循环数组的情况下完成这项工作?

修改

我尝试使用at(index)方法:

this.checkoutFormGroup.get('products').at(index)

但是这会产生错误:

Property 'at' does not exist on type 'AbstractControl'.

编辑2: checkout数据和资金是从服务器收到的。

this.checkoutData.products.forEach(product => {
                    this.fundFormGroupArray.push(this.fb.group({
                        investmentAmount: [this.fund.minInvestment, Validators.required],
                        selectedSubOption: ['', Validators.required],
                    }))
            });

5 个答案:

答案 0 :(得分:33)

将该控件转换为数组

var arrayControl = this.checkoutFormGroup.get('products') as FormArray;

及其所有功能都在那里

var item = arrayControl.at(index);

答案 1 :(得分:6)

虽然在使用at()方法之前将AbstractControl强制转换为FormArray是一种方法,但我还没有看到有人指出您也可以使用get()方法来做到这一点,不需要强制转换。

根据Angular's Documentationget()的签名为:
get(path: string | (string | number)[]): AbstractControl | null

这意味着您也可以使用它访问FormArray的控件。

示例:

const formGroup = new FormGroup({
  list: new FormArray([
    new FormControl('first'),
    new FormControl('second'),
  ]),
});

const firstValue = formGroup.get('list.0').value; // Returns 'first'
const secondValue = formGroup.get('list.1').value; // Returns 'second'

当您想在HTML中绑定FormControl时,这真的很有用,在此处您无法进行任何投射:

<input [formControl]="formGroup.get('list.0')">

以下是执行方法的摘要:

const firstControl = listControl.get('list.0');
const firstControl = listControl.get(['list', 0]);
const firstControl = listControl.get('list').get('0'); // You need a string and not a number
const listControl = formGroup.get('list') as FormArray;
const firstControl = listControl.at(0);

答案 2 :(得分:4)

可以选择一个衬纸作为当前接受的答案

(<FormArray>this.checkoutFormGroup.get('products')).at(index);

答案 3 :(得分:0)

//在.ts组件文件中//

getName(i) {
    return this.getControls()[i].value.name;
  }

  getControls() {
    return (<FormArray>this.categoryForm.get('categories')).controls;
  }

//以反应形式-模板文件//

<mat-tab-group formArrayName="categories" class="uk-width-2-3" [selectedIndex]="getControls().length">
      <mat-tab
        *ngFor="let categoryCtrl of getControls(); let i = index"
        [formGroupName]="i"
        [label]="getName(i)? getName(i) : 'جديد'"
      >
</mat-tab>
</mat-tab-group>

答案 4 :(得分:0)

组件内部:使用这个

(<FormArray>this.checkoutFormGroup.get('products')).at(index).get('yourFormControlName')

在 DOM 内部(在表单控件上应用验证)以这种方式使用它:

<form (ngSubmit)="onSubmit()" [formGroup]="checkoutFormGroup">
   
      <div>
        <h4 >Add Products Below</h4>
      
        <div  formArrayName="products">
          
          <div *ngFor="let subFormGroup of getControls(); let i = index">
            <div class="expense__input" [formGroupName]="i">
              <div class="input__group">
                <label for="Expense Type">Expense Type</label>
                <input type="text" 
                formControlName="productType">
                <span *ngIf="this.expenseForm.get('products').at(i).get('products').invalid">Product Type is Required</span>
              </div>
           </div>
        </div>
      </div>
   </div>