Adding controls dynamically to a form using Angular

Check out the form I created: https://stackblitz.com/edit/angular-ay58g9

I'm encountering an issue when selecting an option from the dropdown menu and I can't seem to figure it out.

Furthermore, I need the output structure to be as follows:

When 'form data' is selected in the dropdown:
[
  data_type: 'form_data',
  form_data: {
    firstname: "saurabh",
    lastname: "Sharma"
  }
]

When 'raw data' is selected in the dropdown:
[
  data_type: 'raw_data',
  raw_data: {
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdcedcc8cfdcdfd5fddad0dcd4d193ded2d0">[email protected]</a>",
    contactno: "9999999999"
  }
]

Could you please take a look at it and let me know what mistake I might be making?

Answer №1

I made some adjustments to the example you provided: https://stackblitz.com/edit/angular-avcytw

In your code, the dynamically added formControls are enclosed within formGroups. It is crucial to include the formGroupName attribute in the parent elements of the inputs.

<div *ngIf="this.form.get('form_data')" formGroupName="form_data">
        <input type="text" formControlName="firstname" placeholder="firstname">
        <input type="text" formControlName="lastname"  placeholder="lastname">
    </div>

Additionally, I modified the initial form setup:

    this.form = this.formBuilder.group({
      data_type: ["", Validators.required],
      // form_data: new FormControl(),
      // raw_data: new FormControl()   
    }); 

The usage of form_data: new FormControl() and raw_data: new FormControl() caused issues with rendering the ngIfs before dynamically adding the corresponding form controls. This resulted in errors stating that the formControls could not be found.

Answer №2

If you're working with Reactive Forms in Angular, I highly recommend exploring the use of FormArray for your forms.

profileForm = this.fb.group({
  firstName: ['', Validators.required],
  lastName: [''],
  formData: this.fb.array([
    this.fb.control('')
  ])
});

For more information, check out the Angular Documentation: https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays

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

Displaying error messages for duplicate inputs in template-driven forms

My current challenge involves implementing required validation for both a text field and a radio button group within a form. The validation works flawlessly for the text field, as shown below: <div class="formControl" [class.error]="carName.touched &am ...

The origin of the Angular img src becomes blurred when invoking a function

I want to dynamically change the image src by calling a function that returns the image path. However, when I attempt to do so using the code below, the image element displays as <img src(unknown)/> component.ts: getMedia(row) { this.sharedData ...

Assign a value to ReplaySubject if it is currently devoid of any

I am facing a challenge with my ReplaySubject in the component after content initialization. Whenever it initializes, it always gets set to "/api/bulletin/getall" value and overrides any value assigned to it before in the onViewChanged function. How can ...

Utilizing MongoDB query for geoLocation with maxDistance parameter

Customer location: customerCoordinates: [83,24] stores: { id:1, location: {coordinates:[85,44]...} maxRadiusDelivery: 2000 //meters }, { id:2, location: {coordinates:[82,34]...} maxRadiusDelivery: 100 //meters } Query: db.wh.find({ 'locati ...

Troubleshooting CAS Single Sign-On with Spring Security and Angular: Dealing with Redirect Loop

I'm currently in the process of integrating CAS SSO into my spring boot application with spring security. The Angular static files are being hosted on the same tomcat server. However, when attempting to access my app, I find myself caught in a continu ...

The Post method encountered an issue when attempting to send an object with a memory size larger than 30MiB, resulting in

When a user interacts with my application, the first step is to select an excel file. This file is then sent to the server for parsing, and an object containing all the rows is returned successfully. (The file only contains numbers and strings, nothing com ...

Programmatically defining the state of the form and inputs as "ng-dirty"

This is my first time dealing with Angular or Angular2, but I've been tasked with updating a website on my domain that uses Angular2. I need to fill out a textbox and submit it programmatically, however even after setting the textbox value using .valu ...

Creating an interface or type in Typescript with a nested object property that uses keys from the same interface

I am looking to create an interface or type that can restrict the nested object properties based on keys defined in the main interface. class MyClass implements MyInterface { prop1: string; promp2: number; nestedObj: { prop1: string; // Allowed a ...

Ionic is encountering a problem with module build, specifically an error related to the absence of a file or directory

Using Ionic has led to encountering the following error message: Runtime Error Uncaught (in promise): Error: Module build failed: Error: ENOENT: no such file or directory, open '/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/r ...

Troubleshooting Issue: Data not appearing on Angular frontend when fetching from Laravel API

Utilizing Laravel for the back end and Angular for the front end development. The code segments related to Angular can be found in employee.component.ts file: import { Component, OnInit } from '@angular/core'; import { DataService } from 'sr ...

Which tool is best suited for generating a diagram within an Angular application?

I am looking to create a project diagram with drag and drop functionality, allowing users to add nodes. I am interested in incorporating a feature similar to the image provided below using Angular9. Can anyone recommend an npm package that is compatible wi ...

Enhance your angular application with universal support using the CLI for Angular 6

After creating a new Angular6 application using Angular CLI, I used the following command: ng generate universal This added support for Universal rendering. Everything is working fine, but I noticed that it also added the following code to my angular.jso ...

"Firebase hosting in Angular experienced an error and was unsuccessful

I am currently using this tutorial to develop a progressive web app with Angular. After creating the project on Firebase, I was able to successfully deploy it. You are now initializing a Firebase project in this directory: /Users/nitish/development/ng ...

Angular + Ionic 4 - Converting String Interpolation to JSON String

I am working with a JSON object that looks like this: { "commands": [ { "command":"begin ${{password}}", "name":"Initialization", "description":"Send SMS begin+password" } ] } How can I dynamically pass data to ${{password}} ...

Tips for avoiding sending empty fields when using Angular's HttpClient.post method

Whenever I try to send data using the POST method to my Rest API in Angular, it ends up sending empty fields resulting in my database storing these empty values. I want to find a way to stop this from happening so that no empty fields are sent from Angula ...

Updating a view based on an SVG object's geometric properties in Angular using effective change detection mechanisms

I'm unsure if there's a proper way to accomplish this in Angular... My goal is managing the overlap of text objects, essentially : Retrieve a list of objects with a date and text description from the backend. Display these objects on an SVG tim ...

React with Typescript: Issue with mapping array not displaying all elements

I am facing an issue with my Table / Array. If I click on the blue button, all items in the same group as the selected record should have their status changed to "Gratis". However, currently, only the value of the selected record and those above it are cha ...

Utilizing cordova-plugin-playlist without prior familiarity with TypeScript

After several years of using Cordova to develop apps, I recently came across TypeScript for the first time. I am currently faced with the challenge of implementing cordova-plugin-playlist without any documentation available, except for an Angular5/Ionic ex ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

Tips for implementing constraints in Angular 8 route parameters

In my Angular web application, I am in the process of configuring routes with parameters. How can I add constraints to ensure only specific IDs are allowed? Below is the path defined in my 'app-routing.module.ts' file: {path: 'post/:id&apo ...