Angular 2: Accessing data from FormArray

前端 未结 4 1055
生来不讨喜
生来不讨喜 2021-01-31 16:23

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

this.checkoutFormGroup = this.fb.group({
                     


        
4条回答
  •  滥情空心
    2021-01-31 16:32

    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 :

    
    

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

提交回复
热议问题