Creating dynamic form fields with Angular 8's reactive forms

I'm struggling with populating form fields from an array. My initial approach was to input the array into a single component that would manage the form instead of creating multiple forms. However, I can't seem to make it work. Any assistance would be greatly appreciated! Despite my efforts on various platforms like Google, Stack Overflow, and Medium, I couldn't find a solution. You can also check out an example on Plunkr here.

In the TypeScript file:

  public demoForm: FormGroup;
  public arrayItems: data = [];

  private formFields = ["Sku", "Title"];

  constructor(private _formBuilder: FormBuilder) {
    this.demoForm = this._formBuilder.group({
      demoArray: this._formBuilder.array([])
    });
  }

  ngOnInit() {
    this.formFields.map(field => {
      this.arrayItems.push({ title: field });
      this.demoArray.push(this._formBuilder.control(''));
    });
  }

  get demoArray() {
    return this.demoForm.get("demoArray") as FormArray;
  }

In the template:

<form [formGroup]="demoForm">
   <div formArrayName="demoArray" 
      *ngFor="let arrayItem of arrayItems; let i=index">
      <input type="checkbox"[formControl]="demoArray[i]">
      <label>{{arrayItem.title}}</label>
   </div>
</form>

Thank you for your help!

Answer №1

Revise your template in the following way:

<form [formGroup]="demoForm">
   <div formArrayName="demoArray" 
      *ngFor="let item of items; let i=index">
      <input type="checkbox" [formControlName]="i"> <!-- this line -->
      <label>{{item.title}}</label>
   </div>
</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

How can elements be collapsed into an array using the Reactive approach?

Consider this TypeScript/Angular 2 code snippet: query(): Rx.Observable<any> { return Observable.create((o) => { var refinedPosts = new Array<RefinedPost>(); const observable = this.server.get('http://localhost/ra ...

Managing Redirects in Angular: Best Practices and Tips

Using spring security has led to a situation where unauthenticated users are redirected to a login page. This causes an issue when an unauthenticated Angular client sends a GET request to an endpoint expecting JSON. Instead of receiving the JSON data, it ...

I am facing difficulty in deploying my Next.js app with Firestore

Having trouble deploying my application using npm run build, Vercel, or another service. It works fine locally without showing any errors. I am using Firebase, Next.js, and TypeScript. The issue seems to be related to getStaticProps. When requesting data, ...

Submitting Additional Information Using Angular 8 and C# Core 3 File Upload Feature

After finally managing to successfully upload files from the Angular 8 frontend to the C# .Net Core 3.0 backend API Controller, I encountered an issue where passing in a separate class along with the files caused an error. The additional class is meant to ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Upgrading from Angular 10 to 13 resulted in an error that required adding 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas'. Although this fix was implemented, the issue still persists and the application remains broken

Here are a few examples of errors: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurred in the template of component ShochatactivestreamviewShellComponent. Error: src/app/money_makers/shochat_guts/shochat_content_creato ...

Issues arise when attempting to use recursive types in combination with optional properties

In my code, I've created a type definition that allows me to traverse an object using an array of strings or indices representing the keys of the object or nested arrays: export type PredicateFunction<ArrayType> = (array: ArrayType, index?: numb ...

Tips on overcoming errors while attempting to create a copy of an object using Spread, especially when the object's class contains abstract methods

In the code snippet below, there is an abstract class that requires extended classes to implement a specific method. However, when utilizing the "spread" syntax, an error occurs due to the missing implementation of the abstract method. abstract class Test ...

JavaScript and TypeScript: Best practice for maintaining an Error's origin

Coming from a Java developer background, I am relatively new to JavaScript/TypeScript. Is there a standard approach for handling and preserving the cause of an Error in JavaScript/TypeScript? I aim to obtain a comprehensive stack trace when wrapping an E ...

The ngModel in Angular 6 did not update the value within the app component

Currently, I am honing my skills in Angular and TypeScript but have encountered a minor issue. Below is the code snippet from my component.html <div> <input [(ngModel)]="mynumber"> N is now {{N}} // some content I want to do with ...

Exploring TypeScript: Implementing a runtime data mapping in place of an interface

Take a look at this code snippet that defines two command handlers for a server: import { plainToClass } from "class-transformer"; enum Command { COMMAND_1, COMMAND_2, } class Command1Data { foo1!: string } class Command2Data { foo2!: ...

Make sure that each function within a generic interface is asynchronous

Imagine having an abstract class that accepts a generic type export abstract class RegisterableClass<InstanceType> and a class that implements it like this: class UserService extends RegisterableClass<IUserService> implements IUserService { ...

Setting up webpack to compile just the necessary assets for running an Angular 5 application

I am currently using Angular 5 and I encountered a situation when running the following command: ng build --prod --named-chunks --aot This command generated numerous files and folders in the 'dist' directory: [development a85a7dc] Initial dist ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...

The 'mat-table' directive is failing to display at its maximum width

Recently, I encountered a peculiar issue with the mat-table directive on a table. Strangely, it doesn't render completely across the screen. Notably, there are no custom styles applied to the table, mat-table, or any elements within it. https://i.sst ...

Issues encountered with rest arguments while setting up gtag

I am currently working on implementing a Google Tag loading script using TypeScript. const GTAG_ID = 'ID'; const script = document.createElement('script'); script.src = `https://www.googletagmanager.com/gtag/js?id=${GTAG_ID}`; ...

What is the process for turning off the suggested action menu for the yellow lightbulb?

Is there a way to remove the yellow lightbulb suggestion menu on this site? It tends to distract me and I rarely use it. Thank you. https://i.sstatic.net/1uzJQ.png ...

Error encountered: Unable to start Angular 5 project - '$' not recognized

I recently downloaded a project and ran npm install. It was running smoothly on my work PC, but now I am facing an issue when trying to start it. The error that keeps popping up is: error TS2304: Cannot find name '$'. This problem is occurring ...

When grouping an array of objects by their property, the error "object index does not have an explicit type" may be encountered

My task involves dealing with an array of objects called Product. The structure of the Product class is as follows: class Product { id: string; type: string; price: number; constructor(id: string, type: string, price: number) { thi ...

Navigating to the Login page in Angular 13

<app-navbar></app-navbar> <div class = "app-body"> <div class="app-sidebar"> <app-sidebar></app-sidebar> </div> <div class="app-feed"> <router-outlet name="main& ...