1

I have a few form fields and want to add more fields dynamically which is coming from another view(where user can enter the form field type, length and name), I Need to construct form fields using these values.

Some how i have managed to construct one field(textbox name is 'one') but if i try to add another field(textbox name is 'two') getting the following error saying,

ERROR Error: Cannot find control with path: 'newfields -> 0 -> two' 

issuecomponent.html

  <form [formGroup]="issuerTestCaseFrm">
                <div>
                    <label for="inputName3">Issuer Reference Number: </label>
                    <input name="lcid" formControlName="IssuerReferenceNumber" required type="tel" class="form-control">
                </div>
                    <div formArrayName="newfields">
                    <div [formGroupName]="i" *ngFor="let tech of issuerTestCaseFrm.controls.newfields.controls; let i = index">
                    <div *ngFor="let prop of fieldProps">
                                <label class="col-sm-2 control-label">{{fields[prop].label}}</label>
                                <div [ngSwitch]="fields[prop].type">
                                    <input *ngSwitchCase="'text'" [formControlName]="prop"> 
                                </div>
                        </div>
                    </div>
                </div>  
    </form>
<button type="submit" (click)="addNewInputField()"> &nbsp;Add New Column &nbsp; </button>

issuecomponent.ts

import { Component, ViewEncapsulation, Pipe, PipeTransform, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl, FormArray } from '@angular/forms';
import { ModalComponent } from '../../modal/modal.component';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
  selector: 'viewhistory',
  templateUrl: './issuecomponent.html',
})


export class IssuerTestcaseExecution implements OnInit {
  issuerTestCaseFrm: FormGroup;
  fields: any;
  fieldProps: any;
  formControls = {};
  constructor( 
    private fb: FormBuilder,  
    public modalService: NgbModal,
    ) {
    this.issuerTestCaseFrm = fb.group({
      'IssuerReferenceNumber': ['', Validators.required],
      'newfields': fb.array([]),
    });
  }

  initNewFields(): FormGroup {
    this.fieldProps.forEach(prop => {
      this.formControls[prop] = [this.fields[prop].value, Validators.required];
    });
    return this.fb.group(this.formControls);
  }

 //Assuming these results coming from modal view after add button click
  addNewInputField(): void {
      const modalRef = this.modalService.open(ModalComponent);
      modalRef.result.then((result) => {
         this.fields = {
          [result.fieldname]: {
            type: result.fieldtype,
            value: result.fieldvalue,
            label: result.fieldname,
          },
        };
        this.fieldProps = Object.keys(this.fields);
         const control = <FormArray>this.issuerTestCaseFrm.controls.newfields;
         control.push(this.initNewFields());
      }, (reason) => {

      });
  }
}

I have added sample code in stackblitz.com. can any body help on this issue: https://stackblitz.com/edit/angular-871vxk?file=src/app/app.component.ts

1 Answer 1

0

although this does not help you completely but there need some changes in form and component to remove this error

  1. change form field to new FormArray()

     this.issuerTestCaseFrm = fb.group({
       'IssuerReferenceNumber': ['', Validators.required],
       'technologies': new FormArray([]),
    });
    
  2. create getter of form filed technologies in the component file.

    get technologies(): FormArray { return this.issuerTestCaseFrm.get('technologies') as FormArray; }
    
  3. in HTML use this way, add formArrayname along with *ngFor and add [formControlName]="i" in your input field.

    <div [formGroupName]="i" *ngFor="let tech of technologies.controls; let i = index" formArrayName="technologies">
    
    <input class="form-control" *ngSwitchCase="'text'" [formControlName]="i">
    
  4. when you click to add button use control.push(new FormControl())

now here you have to work how to add complete formfield

here is the updated demo

Angular FormArray Reference

Sign up to request clarification or add additional context in comments.

3 Comments

I have checked but getting the error in console saying, ERROR Error: Cannot find control with unspecified name attribute
my intention is need to generate dynamic [formControllerName]. so that i can directly send the parameters to database. i stuck up here, kindly look into that issue.
as I said that my answer does not provide the complete solution. you need to work around how to set new formcontrol into your form. check angular form reference.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.