0

In a child component I need to get a FormControl from a parent's FormGroup. It's easy enough to do by injecting FormGroupDirective into the constructor and then calling .control.get() on that injected item.

However, if the form control is actually nested inside of a FormArray, then that doesn't work. What's the equivalent for getting the FormControl from the FormArray?

In my HTML I have just a pretty standard setup

<div [formGroup]="formGroup">
    <ngb-accordion formArrayName="subspaces">
        <ngb-panel *ngFor="let subspace of subspaces; index as i" [formGroupName]=i">
            <my-custom-control controlName="someControlName"

By using the directive I don't have to actually pass in the formGroup. Ideally I wouldn't have to pass the formArrayName or formGroupName to my-custom-control but I can if I have to.

I'm wanting to avoid passing something like this.formArray.at(index).get('someControlName') to the child control. I'm wanting to just pass the controlName and let the child "find" it directly.

I'm not sure how to get the FormArray instance from the FormGroupDirective

Gargoyle
  • 9,590
  • 16
  • 80
  • 145
  • What do you mean by `then that doesn't work` in case of FormArray? What exactly did you try and what's the error? – yurzui Aug 04 '20 at 05:08
  • The call to `this.formGroup.control.get(this.controlName)` just fails saying it can't find the named control. I don't know how to get the `FormArray` instance in the custom control from the form group directive. – Gargoyle Aug 04 '20 at 15:39
  • Can you reproduce your issue in stackblitz? – yurzui Aug 04 '20 at 15:53

1 Answers1

0

You can try using this code

<div [formGroup]="formGroup">
    <ngb-accordion formArrayName="subspaces">
        <ngb-panel *ngFor="let subspace of formGroup.get('subspaces')['controls']; let i =index" [formGroupName]=i">
            <my-custom-control controlName="someControlName"
  • I'm not sure what it is you're showing here. You just changed the syntax of the element being looped over. I already have a list of controls. – Gargoyle Aug 04 '20 at 15:42
  • But as per your code it will not iterate on the formArray .`*ngFor="let subspace of subspaces;` this will search for a variable `subspaces` in the component. – Dhiraj Singh Aug 05 '20 at 05:08