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

You won't find the property 'includes' on a type of 'string[]' even if you're using ES7 features

I encountered a similar issue on another page where it was suggested to modify the lib in tsconfig.josn. However, even after changing compile to es7, the same error kept appearing and the project couldn't be compiled or built. { "compileOnSave": ...

What is the most efficient method to retrieve an API in Angular?

Recently, I dedicated some time to a personal Angular project. While working on it, I decided to experiment with making an API call to PokeAPI in order to retrieve the .svg image of a Pokemon along with its name. After successfully implementing this featur ...

What is the process for extracting the paths of component files from an Angular ngModule file?

I've been on the lookout for automation options to streamline the process of refactoring an Angular application, as doing it manually can be quite tedious. We're working on reducing our app's shared module by extracting components/directive ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

Using Angular 8.x for routing with customized outlet names

I am attempting to set up routing in my Angular 8.x application, utilizing lazy loading and named outlets. Here is the current configuration: main-layout.html <header> <app-top-menu></app-top-menu> </header> <mat-sidenav-cont ...

Exploring the world of nested routes in Angular and how to efficiently

Hey there! I'm brand new to all of this and still trying to wrap my head around a few things, so any guidance you can offer would be awesome! :) Overview I've got a bunch of projects (/projects) Clicking on a project takes me to a detailed sum ...

What is the best way to prevent event propagation in d3 with TypeScript?

When working with JavaScript, I often use the following code to prevent event propagation when dragging something. var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on('dragstart', function(e) { d3.event.sourceEvent ...

Assign a value to a file input in Angular 6

I'm currently working with Angular 6 and I have a requirement to retrieve an image that is dropped into a div element and assign it as the value of an input type="file" within a form. The process involves the user dropping an image into the designate ...

The Angular single-page application fails to refresh when being executed via Visual Studio 2017 Community

I have encountered a problem with my angular 6 app not refreshing when running through Visual Studio 2017. The project consists of multiple projects, including a .NET Core 2 WebAPI and the angular app in question. Even after setting the startup to only be ...

Tips for efficiently managing angular route subscriptions and leveraging parameters for simultaneous http requests

I am seeking the best solution for the following situation: My goal is to trigger two parallel http requests when an Observable from the route parameters subscription fires. I attempted to use switchMap in combination with forkJoin, but unfortunately it ...

Choose the initial mat-option with mat-select functionality

In my app, I have several Angular Material select dropdowns with mat-options that are updated reactively based on other values (filtering of options). Here's an example: <mat-select #selects (selectionChange)='formChanges()' [placeholder ...

Angular component nesting involves placing one component within another component in

When a component is nested inside another, what is that called? For example: <agm-map [latitude]="lat" [longitude]="lng"> <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker> </agm-map> Can you explain how this nesting w ...

What are the best ways to make the most of Angular Material density?

Material has introduced a new density component modifier (Check out the links here and here). After importing material/density, I followed the recommended code structure in my scss file: @use "@material/button"; .my-custom-button { // Adjusts ...

Tips for implementing pagination in ag-Grid with Angular 2

Currently, I am working on developing a grid with pagination feature in Angular 2 using ag-grid. I have already attempted the code below in the HTML file: [gridOptions]="gridOptions" [columnDefs]="columnDefs" [showToolPan ...

Debugging in Next.js and Sanity.io: "Client Components do not support async/await yet, only Server Components."

I am a beginner working on creating a website and e-commerce store using React, Next 14, Typescript, and Sanity as the CMS. I have been following a tutorial available at https://www.youtube.com/watch?v=g2sE034SGjw&t. Encountering the following error: ...

Unrestricted Angular Audio Playback without CORS Restrictions

I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifica ...

Can you include both a routerLink and a click event on the same anchor tag?

I am facing an issue with my li elements. When a user clicks on them, it should open a more detailed view in another component. However, I noticed that it takes TWO clicks to show the data I want to display. The first click opens the component with an em ...

How to style a parent div with a background class in Angular 6

In my Bootstrap 4 project, I am creating an accordion that consists of cards. Each card contains various icons such as edit, view, and details. When any of these icons are clicked, a function in the component is triggered to navigate the user to a child ro ...

Navigating the intricacies of debugging sub-domains in Angular projects using Visual Studio Code (VS

Currently working on a massive project utilizing micro-services. The unique design for clients/tenants requires visiting their specific subdomain to select a particular tenant. For example, https://ClientA.localhost:4200 and https://ClientB.localhost:4200. ...

Dealing with CORS and multiple headers

After setting up CORS for my web api project and deploying it to local IIS, I encountered an issue when trying to call a controller method from Angular. The error message displayed was as follows: SEC7128: Multiple Access-Control-Allow-Origin headers ar ...