Angular 2: Accessing data from FormArray

夙愿已清 提交于 2020-11-30 03:56:43

问题


I have prepared a from using ReactiveForms provided by angular2/forms. This form has a form array products:

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

productFormGroupArray is a array of FormGroup Objects.I fetched the controls i.e. FormArray object using this:

this.checkoutFormGroup.get('products')

I am trying to get the element in the products array at index i. How can this be done without looping through the array?

Edit:

I tried with at(index) method available:

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

but this is generating an error as:

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

Edit 2: checkoutData and fund are received from server.

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

回答1:


Just cast that control to array

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

and all its features are there

var item = arrayControl.at(index);



回答2:


One liner as an option to the current accepted answer

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



回答3:


While casting the AbstractControl to a FormArray before using the at() method is a way of doing it, I haven't seen anybody pointing out that you can also do it using the get() method, which requires no casting.

According to Angular's Documentation, the signature of get() is :
get(path: string | (string | number)[]): AbstractControl | null

Which means you can also access FormArray's controls with it.

Example :

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'

This is really useful, when you want to bind a FormControl in the HTML, where you can't cast anything :

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

Here is a summary of ways of doing it :

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);



回答4:


// in .ts component file //

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

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

// in reactive form - Template file //

<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>


来源:https://stackoverflow.com/questions/40647073/angular-2-accessing-data-from-formarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!