Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Accessing Nested FormArrays using FormBuilder

First of all I just begin with Angular 2 and I'm trying to build a nested form and validate it.

Here's part of my ts file:

ngOnInit() {
  this.myForm = this.formBuilder.group({
    projects: this.formBuilder.array([
      this.initProjects()
    ])
  });
}

initProjects(): any {
  return this.formBuilder.group({
    name: ['', [Validators.required, Validators.minLength(3)]],
    some_array: this.formBuilder.array([
      this.formBuilder.group({
        name: ['', Validators.required],
        attr: ['', Validators.required],
        some_id: [1, Validators.required]
      })
    ])
  });
}

addProject(): void {
  const control = < FormArray > this.myForm.controls['projects'];
  control.push(this.initProjects());
}

View:

<form [formGroup]="myForm" novalidate (ngSubmit)="onSubmit(myForm)">
  <div formArrayName="projects">
    <div *ngFor="let project of myForm.controls.projects.controls; let i = index">
      <div [formGroupName]="i">
        <md-input placeholder="Name" formControlName="name"></md-input>
      </div>
      <div *ngFor="let some_obj of project.controls.some_array.controls; let x = index">
        <div [formGroupName]="x">
          <div>
            <md-input placeholder="Nome" formControlName="controls.some_array.controls.name"></md-input>
            <small *ngIf="!some_obj.controls.name.valid">
                    Nome é requerido
                  </small>
          </div>
          <md-input type="number" placeholder="Cost" formControlName="controls.some_array.controls.attr" required></md-input>
        </div>
      </div>
    </div>
  </div>
  <button type="submit" md-raised-button color="primary" [disabled]="!myForm.valid">Submit</button>
</form>
<pre>form value: <br>{{myForm.value | json}}</pre>

The output of form value:

form value: 
{
  "projects": [
    {
      "name": "",
      "some_array": [
        {
          "name": "",
          "attr": "",
          "some_id": 1
        }
      ]
    },
    {
      "name": "",
      "some_array": [
        {
          "name": "",
          "attr": "",
          "some_id": 1
        }
      ]
    }
  ]
}

Well, as you can see I have some arrays called projects, with 1 array inside each one.

So the problem is that I'm not able to validate each control of some_array array.

Actually I'm getting the following error:

ORIGINAL EXCEPTION: Cannot find control with path: 'projects -> 0 -> controls.some_array.controls.name PS: I already tried to put it in a div, as below:

But I also got an error:

Cannot find control with path: 'projects -> some_array' Thanks in advance. Any help would be appreciated.

like image 735
Deepika Bhandari Avatar asked Oct 13 '16 16:10

Deepika Bhandari


People also ask

How use nested FormArray in ANGULAR?

The only way to build nested forms in angular is by using the FormArray . We show you how to add form fields dynamically in a 2 level nested Form. Our Form will consist of an employee and his skills. The user will be able to add/remove employee's and under each employee, you can add/remove any number of skills.

How do I use FormBuilder?

Using FormBuilder to Generate Controls To use the FormBuilder service, follow the steps below: Import the FormBuilder class. Inject the FormBuilder service. Generate the form contents.

What does FormBuilder do in angular?

The FormBuilder provides syntactic sugar that shortens creating instances of a FormControl , FormGroup , or FormArray . It reduces the amount of boilerplate needed to build complex forms.

What is nested form in angular 14 formarray API?

Angular 14 FormArray API allows creating nested form fields. In this tutorial, we will learn about how to build the nested forms using Angular FormArray API with Reactive Forms. If you are new to Reactive Forms, please refer to Full Angular Reactive Forms & Form Validation Tutorial. What is Nested Form in Angular? 1.

How to create a 2 level nested form in angular?

The only way to build nested forms in angular is by using the FormArray. We show you how to add form fields dynamically in a 2 level nested Form. Our Form will consist of an employee and his skills.

What is the use of formbuilder in angular?

Formbuilder will act as a medium for initializing form array, form control, form group. And, it can be done using the inbuilt methods of the form builder. To use the formbuilder , we want to import formbuilder from the angular forms.

How do I programmatically create a form in angular reactive forms?

In Angular Reactive Forms, every form has a form model defined programmatically using the FormControl and FormGroup APIs, or alternatively using the more concise FormBuilder API, which we will be using throughout this guide.


1 Answers

Try the following HTML:

<form [formGroup]="myForm" novalidate (ngSubmit)="onSubmit(myForm)">
    <div formArrayName="projects">
        <div [formGroupName]="i" *ngFor="let project of myForm.controls.projects.controls; let i = index">
            <md-input placeholder="Name" formControlName="name"></md-input>
            <div formArrayName="some_array">
                <div [formGroupName]="x" *ngFor="let some_obj of project.controls.some_array.controls; let x = index">
                    <div>
                        <md-input placeholder="Nome" formControlName="name"></md-input>
                        <small *ngIf="!some_obj.controls.name.valid">Nome é requerido</small>
                    </div>
                    <md-input type="number" placeholder="Cost" formControlName="attr" required></md-input>
                </div>
            </div>
        </div>
    </div>
    <button type="submit" md-raised-button color="primary" [disabled]="!myForm.valid">Submit</button>
</form>
<pre>form value: <br>{{myForm.value | json}}</pre>
like image 129
Remidy Avatar answered Sep 28 '22 11:09

Remidy