Angular2: Property 'controls' does not exist on type 'AbstractControl'. Error when accessing .control of an object within a formarray thru an index

前端 未结 4 541
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 04:14

I\'m trying to push another formbuilder within a formarray but it gives me an error since I think there are no items in the array when initializing the code, hence there are

相关标签:
4条回答
  • 2020-12-15 04:38

    You can use ['controls'] instead of .controls, as below:

    (<FormArray>this.loanTypeForm.controls['frequency']).controls[index]['controls']['settings'].push(...)
    

    But in order to simplify and provide more readability I'd suggest you to change it all to:

    const control = this.loanTypeForm.get(`frequency.${index}.settings`) as FormArray;
    control.push(...);
    
    0 讨论(0)
  • 2020-12-15 04:44

    It seems that the loanTypeForm is treated as AbstractControl... so let's assure compiler that it is FormGroup

    var group = this.loanTypeForm as FormGroup;
    var array = group.controls['frequency'] as FormArray;
    var control = group.controls[index]; // AbstractControl again.. could be casted as needed
    

    and in case, that control is also group or form we just have to use assert (cast) as well

    var control = group.controls[index] as FormGroup
    

    And then we can easily continue

    control.controls['settings']...
    
    0 讨论(0)
  • 2020-12-15 04:50

    get() is the preferred way to access form controls

    this.loanTypeForm.get(`frequency.${index}.settings`)
    
    0 讨论(0)
  • 2020-12-15 04:51

    below code is working

    <FormArray>this.loanTypeForm.controls['frequency']).controls[index]['controls']['settings'].push(...)
    
    0 讨论(0)
提交回复
热议问题