14

Basically I want to create a dynamic form with nested objects like the picture below: Angular 2 Nested Form Example

  • Pay offs are in an array on the model
  • We should be able to add/remove pay offs as needed.
  • The form should sync underlying form controls and model
  • The number of pay offs is arbitrary and should be loaded into the form from the model

There are no working examples that I could find as how to do this in Angular 2, although this was really easy to do in Angular 1.


Below is my original question, I've since updated it for clarification (see above):

First I just wanted to point out that I'm aware that a new version of Angular 2 rc.2 has just been released a few days ago. So the code for creating a dynamic, nested form may have changed some but there's not enough documentation to figure this out.

In the latest version(s) of Angular 2 (I'm currently using rc.1 but planning to update to rc.2) I need to create a form like this (pseudo-code of view):

<form [ngFormModel]="form" (ngSubmit)="onSubmit()">
  <input type="text" ngControl="name">

  <div *ngFor="let expense for expenses; let i = index;" control-group="expenses">
    <input type="text" ngControl="expense.amount" [(ngModel)]="myModel.expenses[i].amount"> 
    <input type="checkbox" ngControl="expense.final" [(ngModel)]="myModel.expenses[i].final"> 
  </div>

  <a class="button" (click)="addExpenseControl()">Add</a>
  <a class="button" (click)="deleteExpenseControl()">Delete</a>
</form>

So the pseudo-code above won't work but to be honest because of lack of documentation I can't figure out how to wire something like this up. There's a few tutorials about nested ControlGroup but this won't fit the case here since we need to be able to dynamically add and remove control groups, and also I need to be able to sync them with a model.

I found this plunkr here provided by Angular team which allows adding of Controls to a form--but this is not adding/removing a ControlGroup, rather it's using ControlArray and I'm not sure if that applies here?

I'm very familiar with using the newer model-based Angular 2 forms however I'm grasping for resources in order to properly nest them (dynamically!), and tie this nested data into the main form model. How would I refer to nested controls in the view? Is the pseudo-code above even close? I'd post code from my controller but honestly I wouldn't know where to start when it comes to the nested expenses (ControlGroup ??) above...

2
  • A ControlGroup is quite the same as a control and I'm sure you can add it the same way. Jun 22, 2016 at 5:34
  • I was thinking the same, but the question remains even if this is so -- what code do I put for ngControl=".." and [(ngModel)]="..." to correctly wire this up?
    – FireDragon
    Jun 22, 2016 at 9:23

1 Answer 1

16

I had to figure this out on my own because it seems that forms are still changing in Angular 2 and I've not seen any other examples similar to this (although it seems like a very common use-case).

Here is a plunkr of working example using Angular2 RC3.

I am using updated Angular 2 form code from this document.

app.component.ts (contains the form):

import { Component } from '@angular/core';
import {REACTIVE_FORM_DIRECTIVES, FormControl, FormGroup, FormArray} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.html',
  directives: [REACTIVE_FORM_DIRECTIVES],
  providers:  []
})
export class AppComponent {
  form: FormGroup;
  myModel:any;

  constructor() {
    // initializing a model for the form to keep in sync with. 
    // usually you'd grab this from a backend API
    this.myModel = {
      name: "Joanna Jedrzejczyk",
      payOffs: [
        {amount: 111.11, date: "Jan 1, 2016", final: false},
        {amount: 222.22, date: "Jan 2, 2016", final: true}
        ]
    }

    // initialize form with empty FormArray for payOffs
    this.form = new FormGroup({
      name: new FormControl(''),
      payOffs: new FormArray([])
    });

    // now we manually use the model and push a FormGroup into the form's FormArray for each PayOff
    this.myModel.payOffs.forEach( 
      (po) => 
        this.form.controls.payOffs.push(this.createPayOffFormGroup(po))
    );
  }

  createPayOffFormGroup(payOffObj) {
    console.log("payOffObj", payOffObj);
    return new FormGroup({
      amount: new FormControl(payOffObj.amount),
      date: new FormControl(payOffObj.date),
      final: new FormControl(payOffObj.final)
    });
  }

  addPayOff(event) {
    event.preventDefault(); // ensure this button doesn't try to submit the form
    var emptyPayOff = {amount: null, date: null, final: false};

    // add pay off to both the model and to form controls because I don't think Angular has any way to do this automagically yet
    this.myModel.payOffs.push(emptyPayOff);
    this.form.controls.payOffs.push(this.createPayOffFormGroup(emptyPayOff));
    console.log("Added New Pay Off", this.form.controls.payOffs)
  }

  deletePayOff(index:number) {
    // delete payoff from both the model and the FormArray
    this.myModel.payOffs.splice(index, 1);
    this.form.controls.payOffs.removeAt(index);
  }
}

Notice above that I manually push new FormGroup objects into the form.controls.payOffs array, which is a FormArray object.

app.html (contains form html):

  <form (ngSubmit)="onSubmit()" [formGroup]="form">

    <label>Name</label>
    <input type="text" formControlName="name" [(ngModel)]="myModel.name" placeholder="Name">

    <p>Pay Offs</p>
    <table class="simple-table">
      <tr>
        <th>Amount</th>
        <th>Date</th>
        <th>Final?</th>
        <th></th>
      </tr>
    <tbody>
      <tr *ngFor="let po of form.find('payOffs').controls; let i = index">
        <td>
          <input type="text" size=10 [formControl]="po.controls.amount" [(ngModel)]="myModel.payOffs[i].amount">
        </td>
        <td>
          <input type="text" [formControl]="po.controls.date" [(ngModel)]="myModel.payOffs[i].date">
        </td>
        <td>
          <input type="checkbox" [formControl]="po.controls.final" [(ngModel)]="myModel.payOffs[i].final">
        </td>
        <td>
          <button (click)="deletePayOff(i)" style="color: white; background: rgba(255, 0, 0, .5)">x</button>
        </td>
      </tr>
    </tbody>
    <tr>
      <td colspan="4" style="text-align: center; padding: .5em;">
        <button (click)="addPayOff($event)" style="color: white; background: rgba(0, 150, 0, 1)">Add Pay Off</button>
      </td>
    </tr>
    </table>

  </form>

In the html form I link the form to the model on the inputs with statements like so:

... [formControl]="po.controls.amount" [(ngModel)]="myModel.payOffs[i].amount" ...
8
  • i have used find method in html to find out control but in case of .ts i.e controler side angular2 fails to find out the control and throws the error cannot read property push of undefined why ? here is whole problem stackoverflow.com/q/39349261/5043867 ,, thanks in advance Sep 6, 2016 at 13:42
  • @PardeepJain if you are getting the error you mention then it means that whatever FormArray you are trying to call push on is simply undefined at some moment in your code. My guess is that the FormArray isn't being created yet and then you are trying to push a FormGroup onto "nothing". Did you get this working yet? Have you tried my approach to things? My approach uses Model Driven forms, so I am keeping an Angular model in sync with the data as well as the form object.
    – FireDragon
    Sep 8, 2016 at 19:32
  • 1
    For people who are still looking for a good tutorial on the subject, I've found this one (scotch.io/tutorials/…) Hope this helps
    – Nate
    Sep 9, 2016 at 8:11
  • Out of curiosity, what happens when you only want to add a payoffs control if there are payoffs? Then how do you push things into the payoffs' formArray when it is created dynamically? Mar 31, 2017 at 15:33
  • @wolfhoundjesse this code should do what you are asking. If you notice in the constructor I create a model called myModel and this is used to populate the form when it is loaded. You would probably populate your model from a web API and then once you got a response you would run the same code. When this form is loaded it is already populated with the two records I specified so it was written to work as you expect
    – FireDragon
    Mar 31, 2017 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.