vendredi 19 juillet 2019

What is the cleanest way to pass a formGroup to a mat-step?

I'm trying to use the stepper component from angular-material together with reactive forms. The problem is that I don't what is the best way (from an architectural point of view) to allow each mat-step to access a formGroup.

Looking at the two examples below, it seems that the easiest way is to create formGroup1 and formGroup2 outside of the stepper (example 1). My issue with this approach is that inside each <form> I want to have only one custom component that contains its one formGroup and I don't think the container of the stepper should know about the formGroups. Is there any way to achieve this?

<parent that declares formGroup1>
    <mat-vertical-stepper linear>
      <mat-step [stepControl]="formGroup1">
        <form [formGroup]="formGroup1">
            <component that uses formGroup1></component>
        </form>
      </mat-step>
    <<mat-vertical-stepper>
</parent>

<parent oblivious to formGroup2>
    <mat-vertical-stepper linear>
        <mat-step [stepControl]="formGroup2">
            <form [formGroup]="formGroup2">
                <component declaring formGroup2></component>
            </form>
         </mat-step>
    </mat-vertical-stepper>
</parent>

Solutions that I have considered:

  • Declare all formGroups in the parent of the stepper and propagate them to children (downside: seems like too much responsibility on parent and more difficult to understand the code)
  • Declare each formGroup inside child component and emit using @Output() to parent. Use FormArray inside parent so that it's ignorant to the child logic (downside: need to use an index/identifier to make sure the correct form is on the correct position)
  • Use a single form in the parent for the whole stepper

I'd like to know if there's one good solution for this. It feels like I'm missing something very obvious.

Aucun commentaire:

Enregistrer un commentaire