Create an interactive Angular form that dynamically generates groups of form elements based on data pulled from

I am currently developing an Angular application and working on creating a dynamic form using Angular.

In this project, I am attempting to divide the form into two sections: Person Name and Personal Details.

While I have successfully grouped fields for Person Name, I am facing issues with grouping fields for Personal Details.

The HTML:

<div *ngIf="form">
  <div *ngFor="let question of questions" class="form-row" [formGroup]="form">
      <ng-container *ngIf="!question.children">
        <app-question [question]="question" [form]="form"></app-question>
      </ng-container>
      <ng-container *ngIf="question.controlType === 'group' && question.children && question.children.length > 0">
        <app-dynamic-group [questions]="question.children" [form]="form.controls[question.key]" [key]="question.key" [formControlName]="question.key"></app-dynamic-group>
      </ng-container>
  </div>
</div>

JSON:

jsonData: any = [
    {
      "elementType": "group",
      "key": "person_name",
      "children": [
        {
          "elementType": "textbox",
          "class": "col-12 col-md-4 col-sm-12",
          "key": "first_name",
          "label": "First Name",
          "type": "text",
          "value": "",
          "required": true,
          "minlength": 3,
          "maxlength": 20,
          "order": 1
        },
        {
          "elementType": "textbox",
          "class": "col-12 col-md-4 col-sm-12",
          "key": "last_name",
          "label": "Last Name",
          "type": "text",
          "value": "",
          "required": true,
          "order": 2
        }
     ],
    },
        {
      "elementType": "group",
      "key": "personal_details",
      "children": [
        {
          "elementType": "textbox",
          "class": "col-12 col-md-4 col-sm-12",
          "key": "email",
          "label": "Email",
          "type": "text",
          "value": "",
          "required": true,
          "minlength": 3,
          "maxlength": 20,
          "order": 1
        },
        {
          "elementType": "textbox",
          "class": "col-12 col-md-4 col-sm-12",
          "key": "mobile",
          "label": "Mobile",
          "type": "text",
          "value": "",
          "required": true,
          "order": 2
        }
     ],
    },
  ];

The functional Stckblitz: https://stackblitz.com/edit/angular-x4a5b6-5uj52y

Currently, everything seems to be functioning correctly. While I have successfully created a group for Person Name, I am facing difficulty in displaying the input boxes for Personal Details.

The requirement is to split a single form into two parts with titles above each section.

To achieve this structured display, where only the parent title is displayed at the top of each section (e.g., "Person Name (Has First and Last Name)", "Personal Details (Has Email and Mobile)"), I need assistance on how to implement this.

I aim to achieve the following order of display:

Person Name

 -> First Name
 -> Last Name

Personal Details

 -> Email
 -> Mobile Number

If my approach so far is incorrect, I kindly request guidance on splitting the dynamic form as shown in this example.

My goal is to achieve a form layout similar to this example, but incorporating pure Angular dynamic form creation and JSON data loading.

Please assist me in creating a group for Personal Details, akin to how the Person Name group has already been created and is functional.

I have been struggling with this issue for quite some time, your help would be greatly appreciated...

Answer №1

It seems unnecessary to create an additional formGroup in this situation:

this.form = new FormGroup({main: innerForm});

You can simply utilize the formGroup obtained from your service like this:

dynamic-form.component.ts

this.form = this.qcs.toFormGroup(this.questions);

dynamic-form.component.html

<app-dynamic-group [questions]="questions" [form]="form"></app-dynamic-group>

By passing the FormGroup directly to the DynamicGroupComponent, there is no need to implement ControlValueAccessor. The form should be sufficient for dynamic form generation.

dynamic-group.component.ts

@Component({
  selector: 'app-dynamic-group',
  templateUrl: './dynamic-group.component.html'
})
export class DynamicGroupComponent {
  @Input() form: FormGroup;

  @Input() questions: QuestionBase<any>[] = [];
}

dynamic-group.component.html

<div *ngFor="let question of questions" class="form-row">
    <app-question *ngIf="!question.children" [question]="question" [form]="form"></app-question>

    <app-dynamic-group 
       *ngIf="question.controlType === 'group' && question.children && question.children.length"
       [form]="form.get(question.key)"
       [questions]="question.children">
    </app-dynamic-group>
</div>

Forked Stackblitz

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

Does npm run use a separate version of TSC?

I am encountering an issue with my VS Code and Node.js project that uses Typescript. Within my package.json file's script block, there is an entry: "build-ts": "tsc" When I run simply tsc on the integrated terminal command line, the compilation proc ...

When I attempt to navigate using a route on my website, all I see is a

Hey everyone, I'm looking to develop a webpage that switches pages using Navbars. I want to utilize bootstrap and react-route-dom to achieve this functionality. However, before incorporating bootstrap, I encountered some errors that went unnoticed. I& ...

The functionality of the Bootstrap collapse menu is not compatible with Angular

I'm experiencing difficulties with implementing the "collapse" effect in the menu using bootstrap and angular. I have set up the layout separately and everything seems to be functioning correctly, but as soon as I integrate angular, the menu stops wor ...

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...

Issue with running Angular Application through docker-compose.yml file is stopping the execution

Below is the docker file I have created for my angular application: Dockerfile: # base image FROM node:10.16.0-alpine AS build-step # set working directory WORKDIR /app COPY package.json ./ RUN npm install COPY . . RUN npm run build FROM nginx:1.16.1-alp ...

Error encountered while trying to display a Jbuilder JSON object in JSON format

Currently, I am in the process of developing a student tracking website using RoR. Within my model, I have written the following code to construct json: self.as_json json = Jbuilder.new do |j| j.courses student_courses do |course| j.(course, : ...

Which Restlet(Java) libraries are required for performing JSON GET and POST requests?

This question seems to be a repeat of one asked back in 2010, which you can find here. However, considering it's now 2017 and things may have changed, I believe it's worth revisiting this topic. Which libraries are necessary? With the use of ...

The concept of overloading operators in V8

Here's a question that I've been pondering, but couldn't seem to find any answers for on Google. While it may not be achievable in pure JavaScript, let's say I'm developing a container class in V8 and then returning that class bac ...

When transmitting information to the server, the browser initiates four requests

I am encountering an issue with my React component. The problem arises when I try to retrieve the current geographic coordinates, as they are being fetched 4 times consecutively. This same glitch occurs when attempting to send the coordinates to the serv ...

Experiencing a Type Mismatch Error while extracting Summary data

I'm currently developing a Recipe App, and I've successfully managed to parse the JSON data. However, I've hit a roadblock when it comes to implementing a specific section of each recipe: recipe.json Here is an example snippet from a Recip ...

Access various results from a jQuery function

Is there a way to efficiently extract the values of petKeys and employeeKey using the jQuery functions provided below? var whenSelectDateFromCalendar = function () { initKeyValues(); petKeys = ? employeeKey = ? }; var initKeyValues = function ...

Invoke a CoffeeScript function within a jQuery function

Two files are causing me trouble: one is written in plain jQuery, and the other is a Coffeescript The jQuery file looks like this: $(document).ready(function(){ checkPrice(); }); In comparison, the CoffeeScript file appears as follows: $ -> c ...

Using Mocha in Node to make XMLHttprequests

Currently, I am experimenting with using node-xmlhttprequest. Here is an example of what I have been working on: // f.js (function() XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest xhr = new XMLHttpRequest() xhr.open('GET ...

Verify the string to see if it contains a Steam game key

I am seeking assistance with a task that involves verifying whether a specific string contains a particular pattern: Below are several strings in an array: [ "please use this key: ')D9ad-98ada-jiada-8a8aa'", "kK8AD-AODK8-ADA7A", "heres a fr ...

send image back to Angular component from server response

I'm extremely close to achieving my goal. The server is successfully returning the image and sending it in the response. Now, the challenge lies in getting my angular component to properly display it. Let me share what I have done so far: Firstly, h ...

Changing mySQL database queries into JSON format using PHP

I've been trying to connect to my local database and retrieve results from a table using the code below. However, I'm having trouble with printing the results in JSON format. Can you please review the code and let me know if there's anything ...

Improving the utilization of services in Angular

I have a DatesService that handles date manipulation. Additionally, I have two services that require date manipulation - EventsService and CalendarService. The CalendarService utilizes the EventsService. My query is: what would be more efficient (in terms ...

Unable to convert the String value into a java.time.LocalDate object

I am struggling with formatting the json payload for my Entity Class ImportTrans. The eventTime type is currently set to LocalDate, but I need to find a way to make it accept the json input format. { "eventId":"ep9_0579af51-4b5c", " ...

PHP WebService, exclusively containing private variables within an empty array

I'm attempting to create a PHP webservice. In the "Aluno" class, there are 2 private variables. After struggling all day with this, I finally discovered that if I change those variables to public, everything works as expected. However, if they remain ...

Is it possible to prevent the selected option from being available in other select lists using AngularJS?

Can anyone help me figure out how to disable an option in one select list when it is selected in another using AngularJS? I have set up a select list for From Year and To Year with ng-repeat, which is working fine. Now, I just need to implement the functio ...