0

i'm trying to do nesting of form array in angular 11. As of now I have try like this and it working fine.


spinner: boolean = false;
  new_created: boolean = true;
  create_question_form: FormGroup;
  group: any = new FormGroup({
    name: new FormControl(''),
  });

  constructor(private route: ActivatedRoute, private fb: FormBuilder) {}

  validation() {
    this.create_question_form = this.fb.group({
      question: new FormArray([this.group]),
    });
  }

  get question() {
    return this.create_question_form.get('question') as FormArray;
  }

  add_question() {
    this.question.push(this.group);
  }

  create_question() {
    const data = this.create_question_form.getRawValue();
    console.log(data);
  }

  ngOnInit(): void {
    this.validation();
    this.add_question();
  }
 <form
            [formGroup]="create_question_form"
            (ngSubmit)="create_question()"
          >
            <ng-container formArrayName="question">
              <div *ngFor="let _ of question.controls; index as i">
                <ng-container [formGroupName]="i">
                  <div class="col-12 col-md-4 mt-5">
                    <span class="p-float-label w-100">
                      <input
                        type="text"
                        id="inputtext"
                        class="form-control"
                        formControlName="name"
                        pInputText
                      />
                      <label for="inputtext">Name</label>
                    </span>
                  </div>
                </ng-container>
              </div>
            </ng-container>

            <button type="submit" class="btn btn-success">Create</button>
          </form>

But what I want is to create a new FormArray (Address) inside my Formgroup something like this.

 group: any = new FormGroup({
    name: new FormControl(''),
    address:new FormArray([]),
  });

I don't have any idea how can I access this address form array in my HTML or how can I push new FormControls in this array.

Mohd Sabban
  • 182
  • 1
  • 12

2 Answers2

0

for adding a new group: this.group.controls.address.push(new FormGroup({street: new FormControl('')}));

for accessing that added group: this.group.controls.address['controls'][0]['controls']['street'].value

for removing that group: let group_arr = (this.group.controls.address as FormArray); group_arr.removeAt(index)

0

to add the form group :

this.group.controls.address.push(new FormGroup({street: new FormControl('')}));

to use in template :

in ts:

get addresses(): FormArray {
    return this.group.controls.address as FormArray;
}

in html :

<ng-container *ngFor="let address of addresses.controls">
  <form [formGroup]="address">
    <input type="text" formControlName="street">
  </form>
</ng-container>
jagjeet
  • 585
  • 2
  • 10