fivedoor fivedoor - 2 months ago 39
Javascript Question

angular2 using input to dynamically add to form model

This is to some extent a dupe of this question but hopefully less convoluted.

Is it possible to to add a completely new FormGroup via a form input where the new FormGroupName can be defined via input? If so which directives or functions would I use to achieve this?

User Case:

The user can define a new FormGroupName via input field and click to extend the form with the new FormGroup, then fill out values for that FormGroup’s FormControls.

1 User fills out an existing 'name' field as normal.

2 Types ‘foo’ into an input field

3 Clicks ‘add data group’ to create the new FormGroup 'foo'

4 The form reveals input fields for 'height' and 'weight' for the new FormGroup foo.

5 User fills out 'height' and 'weight' values for 'foo'

6 Repeats step 2-5 for 'bar'

7 Submits:

{
"name":"Data Form",
"foo":{
"height":"6.00",
"weight":"300"
},
"bar":{
"height":"5.11",
"weight":"260"
}
}


The FormControls in the added FormGroups will always be consistent.
So as in the above example always ‘weight’ and ‘height’.

The intention is to use the form as a basic UI to help generate some JSON data.

Thanks.

Answer

The solution I came up with was to use a dynamic [formGroupName] which references an array which is updated each time a new group is added

[formGroupName]="myGroupName[i]"

app.component.ts :

import { Component, OnInit } from '@angular/core';
import { Customer } from './customer.interface';
import { FormControl, FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';


@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.component.html',
})
export class AppComponent implements OnInit {
    public myForm: FormGroup;

      myGroupName = ['test'];


    constructor(private _fb: FormBuilder) { 
    }

    ngOnInit() {
        this.myForm = this._fb.group({

            myArray: this._fb.array([
                this._fb.group({  
                   test: this._fb.group({
                        name: ['test'],
                            title: [''],
                          link: [''],
                            cta: [''],

                    })
                }), 

            ])
        });
    }


 initArray(nameObj:any) {
      return  this._fb.group({  
                [nameObj]: this._fb.group({
                        name: [nameObj],
                          title: [''],
                        link: [''],
                          cta: [''],

                    })
                })
    }

 addArray(newName:string) {
        const control = <FormArray>this.myForm.controls['myArray'];
        this.myGroupName.push(newName);
        control.push(this.initArray(newName));
            document.getElementById('newName').value='';
    }



  removeDataKey(i: number) {
       const control = <FormArray>this.myForm.controls['myArray'];
       control.removeAt(i);
       this.myGroupName.splice(i,1);
    }

}

app.component.html:

<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)">

      <div formArrayName="myArray"> 

         <div *ngFor="let myGroup of myForm.controls.myArray.controls; let i=index" class="panel panel-default">

           <div [formGroupName]="i" class="panel-body"> 
              <span *ngIf="myForm.controls.myArray.controls.length > 1" 
                    (click)="removeDataKey(i)" class="glyphicon glyphicon-remove pull-right">
                </span>
             <h5 >Group {{i + 1 }}</h5>
            <h3>  {{myGroupName[i] }}</h3>

              <!--[formGroupName]="myGroupName[i]"-->
              <div [formGroupName]="myGroupName[i]" class="panel-body"> 


              <div class="form-group">
              <label>Title</label>
              <input type="text" class="form-control" formControlName="title" >
              </div>

              <div class="form-group">
              <label>Link</label>
              <input type="text" class="form-control" formControlName="link" >
              </div> 

              <div class="form-group">
              <label>Cta</label>
              <input type="text" class="form-control" formControlName="cta" >
              </div>


              </div>
              <!--[formGroupName]="myGroupName[i]"-->

        </div>
         <!--[formGroupName]="i" -->
      </div>

    </div>
     <!-- myArray array-->

        <div class="margin-20">

        <input #newName
      (keyup.enter)="addName(newName.value)"
       type="text" style="width:30%" id="newName">


        <a (click)="addArray(newName.value)" style="cursor: default" class="btn">Add Group  +</a>



        </div>
</form>

The dupe of this question is also answered here with related plunks