Home > Mobile >  How to use nested FormGrups inside FormArray
How to use nested FormGrups inside FormArray

Time:06-20

I am doing a little Angular project, but I am having problem using controls inside a FormGroup, which is inside a FormArray. The 2 controls "name" and "hc", works fine, but "hole1", which is inside another formGroup, is bugging me. Any help please ?

TS

import { Component, OnInit } from '@angular/core';
import { FormGroup,FormArray, FormBuilder } from '@angular/forms'

@Component({
  selector: 'app-scorecard',
  templateUrl: './scorecard.component.html',
  styleUrls: ['./scorecard.component.scss']
})
export class ScorecardComponent implements OnInit{
  title = 'FormArray Example in Angular Reactive forms';
  roundForm: FormGroup;

  constructor(
    private fb:FormBuilder
    ) {}

  ngOnInit(): void {
    this.roundForm = this.fb.group({
      name: 'Round',
      persons: this.fb.array([this.newPerson()])
    });
  }

  get persons() : FormArray {
    return this.roundForm.get("persons") as FormArray
  }

  newPerson(): FormGroup {
    return this.fb.group({
      name: '',
      hc: '',
      holes: this.fb.group({
        hole1: null
      })
    })
  }

  addPerson() {
    this.persons.push(this.newPerson());
  }

  removePerson(i:number) {
    this.persons.removeAt(i);
  }

  onSubmit() {
    console.log(this.roundForm.value);
  }

}

HTML

    <form [formGroup]="roundForm" (ngSubmit)="onSubmit()">
    
      <!-- <strong>
        {{roundForm.get('name')}}
      </strong> -->
    
      Persons:
      <div formArrayName="persons">
        <div *ngFor="let person of persons.controls; let i=index">
          <div [formGroupName]="i">
            {{i}} <br>
            <input type="text" formControlName="name"> <br>
            <input type="text" formControlName="hc">
**I want input with hole1 here**
    
            <button (click)="removePerson(i)">Remove</button>
          </div>
        </div>
      </div>
      <button type="submit">Submit</button>
    </form>
    
    <button type="button" (click)="addPerson()">Add</button>
    
    <pre>{{this.roundForm.value | json}}</pre>

CodePudding user response:

You just need to specify the hole group form control, and then use the inner form control name:

...
<input type="text" formControlName="name"> <br>
<input type="text" formControlName="hc">
<div formGroupName="holes">
  <input type="text" formControlName="hole1">
</div>

Demo

  • Related