Encountering Issue: Unable to locate control with the given name in Angular when generating Dynamic Form with FormGroup

As a beginner in Angular, I aim to develop a dynamic Survey Form that can adjust its questions and input types based on the area. These changes are fetched as JSON data through API calls.

Here is the relevant code snippet:

.ts File

export class MaintenanceSurveyComponent implements OnInit {
  myFormTemplate: any = []; 
  myFormGroup: FormGroup = new FormGroup({});
  
  WOId;
  @Input() public user;
  constructor(private maintenanceService: MaintenanceRequestService) { }

  ngOnInit() {
   this.myFormGroup = new FormGroup({});
    this.maintenanceService.getSurveyquestions(this.user)
      .subscribe((res: any) => {
        this.myFormTemplate = JSON.parse(res);        
    });
    let group = {}
    this.myFormTemplate.forEach(input_template => {
      group[input_template.hMy] = new FormControl({ value: input_template.hMy});
    })
    this.myFormGroup = new FormGroup(group);    
  }

  onSubmit() {
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myFormGroup.getRawValue(), null, 4));
    console.log(this.myFormGroup.getRawValue());
    console.log("this is test");
  }

}

.html File

<form [formGroup]="myFormGroup" (ngSubmit)="onSubmit()">
    <div class="modal-header border-0">
      <h5 class="modal-title" id="addMaintenanceRequestsTitle">Maintenance Survey</h5>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <div class="row">
        <div class="col-lg-7">

          <div *ngFor="let form_elem of myFormTemplate">
            <div [ngSwitch]="form_elem.type">
              <div class="form-row">
                <div class="form-group col-md-12 mb-2" *ngSwitchCase="'textbox'">
                  <label class="text-sm font-weight-bold mb-1">{{form_elem.label}} </label>
                  <input type="text"  formControlName="{{form_elem.hMy}}" required="{{form_elem.IsRequired}}" ngDefaultControl />
                </div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-12 mb-2" *ngSwitchCase="'number'">
                  <label class="text-sm font-weight-bold mb-1">{{form_elem.label}} </label>
                  <input type="number" formControlName="{{form_elem.hMy}}" required="{{form_elem.IsRequired}}" ngDefaultControl />
                </div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-12 mb-2" *ngSwitchCase="'select'">
                  <label class="text-sm font-weight-bold mb-1">{{form_elem.label}} </label>
                  <select  formControlName="{{form_elem.hMy}}" required="{{form_elem.IsRequired}}" ngDefaultControl >
                    <option *ngFor="let opt of form_elem.options">
                      {{opt}}
                    </option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-footer justify-content-start">
      <button type="submit" value="save" class="btn btn-primary">Submit</button>
    </div>
  </form>

Error:

ERROR Error: Cannot find control with name: 'textbox88'
    at _throwError (forms.js:2293)
    at setUpControl (forms.js:2201)
    at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:5427)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:6028)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:5949)
    at checkAndUpdateDirectiveInline (core.js:21092)
    at checkAndUpdateNodeInline (core.js:29494)
    at checkAndUpdateNode (core.js:29456)
    at debugCheckAndUpdateNode (core.js:30090)
    at debugCheckDirectivesFn (core.js:30050)

I have attempted different solutions without success. Any assistance on this matter would be greatly appreciated. I am currently using Angular 8.

Answer №1

It is important to ensure that the form creation is placed inside the subscribe method and that you wait for the response due to it being an asynchronous call.

export class MaintenanceSurveyComponent implements OnInit {
    myFormTemplate: any = [];
    myFormGroup: FormGroup = new FormGroup({});

    @Input() public user;
    constructor(private maintenanceService: MaintenanceRequestService) {}

    ngOnInit() {
        this.myFormGroup = new FormGroup({});
        this.maintenanceService.getSurveyquestions(this.user).subscribe((res: any) => {
            this.myFormTemplate = JSON.parse(res);

            let group = {};
            this.myFormTemplate.forEach((input_template) => {
                group[input_template.hMy] = new FormControl({ value: input_template.hMy });
            });
            this.myFormGroup = new FormGroup(group);
        });
    }

    onSubmit() {
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myFormGroup.getRawValue(), null, 4));
        console.log(this.myFormGroup.getRawValue());
        console.log('this is test');
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for setting a default checkbox as checked in Angular 6?

example.component.html <form method="post" enctype="multipart/form-data> <mat-checkbox class="style" name="checkboxenabled"[(ngModel)]="checkboxObj.checkboxenabled">Enabled</mat-checkbox> </form> I have been trying to set the c ...

Switching up the icons of Angular/PWA in Ionic 5 - here's how!

Is there a way to change the default icons from @angular/pwa using "ionic cordova resources" command? I have tried this but the icons still remain unchanged. Any suggestions on how to achieve this? ...

Preventing angular mat-menu from closing when clicking outside of it: simple solutions

When implementing MatMenu as a popup for guiding new users on my web app, I prefer not to close it when the user clicks outside of it. I've successfully used $event.stopPropagation() to prevent closure when clicking a button within it. Now, I'm ...

"Uploading user profile images with Angular, Express, Multer, and Mongoose made easy

Hey there, I'm currently using multer to upload images. When I select an image, it gets saved in the backend folder called uploads. However, I would like to store it in a MongoDB database and then display that image on the frontend using Angular. I&ap ...

typescript - instantiate an object using values stored in an array

Assume we have a model defined as follows. export interface Basicdata { materialnumber: number; type: string; materialclass: string; } We also have an array containing values that correspond directly to the Basicdata model in order, like this: ...

Issues Encountered when Installing Angular on a Mac

While attempting to install angular on my MacBook, I encountered some confusing errors. Below is a snippet of the terminal commands I used: S-MacBook-Pro-491:~ s$ node -v v8.9.4 S-MacBook-Pro-491:~ s$ npm -v 5.6.0 S-MacBook-Pro-491:~ s$ npm install -g @a ...

Is there a way to make divs expand on top of existing content when hovering over them, in order to avoid needing to scroll through overflow content? I am currently working with

I am working with 9 boxes contained within divs, each box includes data that exceeds the size of the box itself (represented by Some Text repeated for demonstration purposes). I am seeking a solution where hovering over any box will cause it to enlarge and ...

The canActivate: [AuthGuard] feature on the external router is not functioning as expected

I'm encountering an issue with my routing. I attempted to use the following code: const routes: Routes = [ { path: 'home', component: HomeComponent, canActivate: [AuthGuard], children: [ { path: 'events', component: Ev ...

Angular2 (AngularCLI) cannot locate the Elasticsearch module

Currently, I am attempting to incorporate the Elasticsearch NPM Module into my Angular2 application. In order to use it in my service, I have imported it as follows: import { Client, SearchResponse } from 'elasticsearch'; Even though there are ...

Tips for mocking a module with a slash character in its name?

When it comes to mocking a standard npm project, the process is simple. Just create a __mocks__ folder next to the node_modules folder, then name the file after the package and insert the mock contents. For example: /__mocks__/axios.ts However, I encount ...

"Troubleshooting Angular Reactive Forms: Issue with Dropdown Displaying Incorrect Selected Value

Currently, I'm in the process of constructing a Reactive form using Angular 9 which involves incorporating a dropdown. The code snippet below illustrates the dropdown component: <form [formGroup]="registerForm" (ngSubmit)="onSubmit()"> ... ...

Conceal a division based on its numerical position

I'm having trouble figuring out how to hide multiple divs based on an index that I receive. The code snippet below hides only the first div with the id "medicalCard", but there could be more than one div with this id. document.getElementById("medical ...

Use a function on values that have corresponding keys in a separate array

I am working with a form.value object that looks like this: form.value = { "to_date": "2019-03-21T05:00:00.000Z", "from_date": "2019-03-13T05:00:00.000Z", "is_form": "" "errors":"" } Additionally, I have an array called filterArray: filterArray ...

Selecting a GoJS Node using keys

In Angular with TypeScript, what is the best way to select a node from a diagram based on its key? Currently, I am required to left-click a newly created node in order to select it, but I would like for it to be automatically selected upon creation. I ha ...

Issue with string interpolation failing to correctly reflect the updated value from the service provider

I created a simple component to test string interpolation in HTML, <p>{{value}}</p> Here is the TypeScript file: export class HelloComponent implements OnInit { value: any; constructor(private service: ApiService) { this.value = ...

Mastering the Art of Flex Layout Grids

Here is a preview of how my grid is currently formatted: https://i.stack.imgur.com/SBChV.png The current code looks like this: <div fxLayout="row wrap"> <img class="component-logo" fxFlex="1 1 c ...

Can a TypeScript interface inherit from multiple other interfaces simultaneously?

Hello Angular Community, I have a question regarding nesting three interfaces within another interface. Let me explain with some code: I am attempting to integrate the IProject1, IProject2, and IProject3 interfaces into the IAdmin2 interface: Thank you ...

Assembly of these elements

When dealing with a structure where each property is of type These<E, A> where E and A are unique for each property. declare const someStruct: { a1: TH.These<E1, A1>; a2: TH.These<E2, A2>; a3: TH.These<E3, A3>; } I inte ...

Combine the AnimatedMarker from leafletjs with typescript

After installing leaflet typescript, I encountered issues when trying to use leaflet non-typescript plugins. For instance, I had no problem importing the leaflet-routing-machine plugin by following these steps: installation: npm install --save leaflet-ro ...

Ensure that child components' property types are enforced in TypeScript

I am trying to enforce the type of a property in a child component. I expected the code below not to compile because Child's property name is not correctly typed inside Parent within the app. However, there is no compiler warning displayed. Is there ...