Creating an Angular form group that includes dynamic form controls with custom form control names

Seeking to implement a formGroup that dynamically adjusts based on JSON data like this:

  const LIMITS: Limit[] = [
  {
    id: 'limit1',
    value: 1000,
    disabled: false
  },
  {
    id: 'limit2',
    value: 500,
    disabled: true
  },
  {
    id: 'limit3',
    value: 5000,
    disabled: true
  }
]

While utilizing formArray as suggested in this explanation produces desired results, there is an issue with losing the essential `id` information needed for matching edited values. Is there a method to generate a dynamic form with custom `formControlName` identifiers? Take a look at the StackBlitz example based on the same enquiry here.

UPDATE


Previously attempted using `FormGroup`, but encountered errors upon initialization.

Error: Cannot find control with path: 'limits -> limit1'
Error: Cannot find control with path: 'limits -> limit2'
Error: Cannot find control with path: 'limits -> limit3'

Realizing that when inputs are...refer to this StackBlitz demo for further insights here.

UPDATE


Solution was discovered by defining `limits` and employing `setControl` during data subscription.

 ngOnInit() {
    this.form = this.fb.group({
      limits: this.fb.group({})
    })

    this.limits$.subscribe((limits: Limit[]) => {
      this.form.setControl('limits', this.addLimits(limits));
    });

  }

Check out the interactive StackBlitz demonstration here

Answer №1

If you prefer utilizing the id attribute as a primary identifier, consider employing FormGroup in place of FormArray. Utilize addControl and removeControl rather than push and removeAt to maintain the dynamic nature of your form.

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

Breaking up and Substituting text within Angular 8's HTML structure

When I retrieve data from a REST api, I need to split the name parameter at '2330' and insert a line break. For example, if the name is: ABCD 2330 This is My Name, I want the output on my screen to appear as: ABCD 2330 This is My Name // this par ...

When utilizing the Map.get() method in typescript, it may return undefined, which I am effectively managing in my code

I'm attempting to create a mapping of repeated letters using a hashmap and then find the first non-repeated character in a string. Below is the function I've developed for this task: export const firstNonRepeatedFinder = (aString: string): strin ...

Exploring Angular2: Incorporating External Plugins with AngularCLI (webpack)

Currently, I am in the process of developing an Angular2 application using AngularCLI with webpack version. A third-party plugin called ScrollMagic is being utilized which comes with optional plugins of its own. The main codebase for ScrollMagic has been i ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...

Angular 2: Implementing service functions on button click using the (click) event

Is it possible to call a function from my service when clicking on an element in the HTML returned from an HTTP call? Here is the HTML snippet: <a (click)="SellingVarietiesService.goToVarietyDetails(3)">Test</a> The function I want to call i ...

Angular is generating local caches of NPM packages within the designated .angular folder

Is there a way to turn off the caching in the main Angular project directory? I noticed this issue after setting up NVM last week. ...

Error in Angular SSR: Build failed due to project reference without "composite" setting set to true

Currently facing an issue while developing an Angular App with SSR. When using npm run build:ssr, the following errors are displayed: ERROR in [...]/tsconfig.json [tsl] ERROR TS6306: Referenced project '[...]/tsconfig.app.json' must have se ...

Creating a search functionality in Angular that allows users to input multiple search terms and

I am currently delving into the world of Angular in combination with an API, and I have managed to set up a search box for querying data. However, I am facing a challenge where I cannot perform multiple searches successfully. Even though I can initially se ...

Cannot get Typescript Module System configuration to function properly

I'm encountering an issue with my existing TypeScript project where I'm trying to change the module type to System, but despite setting it in the project properties, the compiler always outputs in AMD format (define...). It's frustrating be ...

Modify the class of the focused element exclusively in Angular 2

I'm working on a project that involves several buttons and div elements. Currently, the divs are hidden, but I want to be able to reveal a specific div when its corresponding button is clicked. For example: If you click the first button, only the fir ...

Developing Designs in the Angular versions 5/6

I'm encountering an issue with displaying the answer from the backend (JSON). Here is the JSON data received from the server: { "items": [ { "countryId": 1, "countryName": "Особь без подданства", "countryIdEDBO": -1, ...

What could be the reason my mat-form-field is not displaying the label?

I'm currently working on a project using Angular Material to build a web page. I am facing an issue with the mat-form-field component as the label is not displaying, and I can't figure out why. Any assistance would be greatly appreciated. Thank y ...

What are the best methods for protecting a soda?

My code is in strict mode, and I am encountering an issue with the following snippet: const a: string[] = []; // logic to populate `a` while (a.length > 0) { const i: string = a.pop(); // This line is causing an error console.log(i); // additio ...

Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed. Uncaught TypeError: Cannot read p ...

Discovering the true rendering elements in karma tests: A guide

Recently, I started working on a new project in Angular14. However, when I completed writing the unit tests, all I could see was a series of successful text information and not any HTML elements displayed. How can I view the HTML elements? ...

Encountering a style-loader error while trying to upgrade to Angular 15 using @angular-builders/custom-webpack

Check out my demo repository at the following link: https://github.com/OrShalmayev/style-loader-error After upgrading my Angular project from version 12 to 15, I encountered an issue with my angular.json file configuration: "architect": { &q ...

The modal popup will be triggered by various button clicks, each displaying slightly different data within the popup

As a newcomer to Angular 4, I have encountered an interesting challenge. Currently, my code consists of two separate components for two different modals triggered by two different button clicks (Add User and Edit User). However, I now face the requiremen ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

What is the key to mastering any concept in Angular2 for optimal results?

When creating a Pipe to filter data, I often use the datatype any, allowing for flexibility with types. However, I have some questions regarding this approach: Is it considered a best practice? Does it impact performance when handling large amounts of da ...

Combining pixijs with TypeScript in Ionic 2 using npm

To begin, I ran the command npm install -g ionic Followed by ionic start pixiApp blank --v2 Navigated to the pixiApp directory with cd pixiApp Installed necessary dependencies using npm install Added a specific version of pixi.js (4.1.0) with npm install p ...