0
form( [formGroup]="form" )
  div( '[formGroupName]'="formGroupName" )
    .form-group
      label
        | Address
      input.form-control(
        type="text"
        formControlName="address"
      )
  div(formArrayName="sub_addresses_attributes")
    div(
      '*ngFor'="let sub_addresses_attribute of form.get('sub_addresses_attributes')['controls']; let i=index"
    )
      div( '[formGroupName]'="i" )
        .form-group
          label
            | Address
          input.form-control(
            type="text"
            formControlName="address"
          )

I would like to create a component or partial or template that can DRY-up the code above.

This is may parent/main component: parent.component.ts

this.fb.group({
  'sub_addresses_attributes': this.fb.array([]),
  'address_attributes': {
    'id': [],
    'address': []
  }
}

Here the partial component I am trying to create

div( '[formGroup]'="FROM_@INPUT" )
  div( '[formGroupName]'="FROM_@INPUT" )
    .form-group
      label
        | Address
      input.form-control(
        type="text"
        formControlName="address"
      )

However, formGroupName is required for the address_attributes, while not on formArray.

dr.calix
  • 667
  • 8
  • 21
  • Use ngForm. It very eases validation compared to formGroup. Ref link: https://angular.io/api/forms/NgForm My simple stackoverflow example link: https://stackoverflow.com/questions/52760992/ngform-simple-example-in-angular-6-with-select-box#52760993 – Jai Kumaresh Feb 16 '20 at 06:46

1 Answers1

0

I have found that when splitting out forms into reusable components, the form group needs to be set on the innermost component that contains the form control itself.

My component hierarchy is something like this, where each my-* component is a different custom component:

<my-form>
  <my-form-controls>
    <my-form-control *ngFor="let control of controls">
      <div #controlcontainer>
      </div>
    </my-form-control>
  </my-form-controls>
</my-form>

I then inject the form control itself into #controlcontainer. The controls themselves looks something like:

<div [formGroup]="formGroup">
  <input [name]="name" />
</div>

When creating this hierarchy, I found that [formGroup] has to be set on the component that hosts the input - it doesn't get inherited from parent components.

If I understand your question correctly, I think you want to achieve something fairly similar - reuse form components and use [formGroup].

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
  • I have updated my question which I hope will to make it clearer. Main issue right now I am encountering is for not formArray control, it requires formGroupName. – dr.calix Feb 16 '20 at 10:50