Home > Mobile >  Is it possible to nest forms two levels deep in Angular?
Is it possible to nest forms two levels deep in Angular?

Time:01-26

I need to nest a formgroup two levels deep for a functionality in an Angular project. This is the situation:

I have multiple small formgroups. These all have a common parentform. For a new page I need one seperate formgroup and all the children of the parentform. I'm trying to create a new parentform that has two children: the seperate formgroup and the first parentform.

I'm trying to do it this way to avoid too much duplicate code. The structure I'm trying to end up with looks like this:

child formgroups \
                  ==> original parentform \
                                           ==> new parentform
                       seperate formgroup /

Currently I'm importing both the original parentform and the seperate formgroup in the same way. ie: parentform.AddControl('seperate', seperate formgroup); parentform.AddControl('original parent', parentform);

The problem I'm running into is that the form itself is being updated but the object in the body of the PUT request is not.

Is it at all possible to use formgroup nesting more than one level deep?

CodePudding user response:

Yes!!! Angular allows for creating nested forms by using the ngModelGroup directive to create a nested FormGroup within the parent FormGroup.

Below is code example:

<form [formGroup]="parentFormGroupName">
   <div formGroupName="firstLevelGroupName">
      <input formControlName="firstLevelControl" ..>
      <div formGroupName="secondLevelGroupName">
         <input formControlName="secondLevelControl" ..>
      </div>
   </div>
</form>

In this example, the parentFormGroupName is the top-level FormGroup, and it contains a firstLevelGroupName FormGroup, which in turn contains a secondLevelGroupName FormGroup. With many levels, the complexity increases, and becomes hard to manage the forms.

Also, you need to define each level of FormGroup in your component class & link it to the template with the correct bindings. If you want to access the controls & the values of the nested forms you should use the correct path to access them.

CodePudding user response:

Yes it is,

  form!: FormGroup;
  
  constructor(private formBuilder: FormBuilder) {
     // incialize form structure
     this.form = this.formBuilder.group({
      1: ['', Validators.required],
      2: this.formBuilder.group({
        2_1: ['', [Validators.required]],
        2_2:  ['', [Validators.required]],
      })
    });
  }

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <input type="text" formControlName="1" />

    <div  formGroupName="2">
      <input type="text" formControlName="2_1" />
      <input type="text" formControlName="2_2" />
    </div>
  </div>

  <button [disabled]="loading" >Submit</button>
</form>

and so on ...

  • Related