What is the best way to connect a series of checkboxes within a form utilizing Angular?

I created a form with checkboxes that allow users to select multiple options. However, when I submit the form, instead of receiving an array of objects representing the checked checkboxes, I'm not getting anything at all.

Here is what I see in the console: {fruits: Array[0]}

What I was hoping for:

{fruits: Array[1]} // The number of items in the array should correspond to the number of checkboxes selected

You can take a look at an example on stackblitz for reference

Answer №1

All the steps have been completed except for initializing the form

myForm: FormGroup = this.initializeModelForm();

The complete code snippet includes the console logging of the formArray value

import { Component } from '@angular/core';
import { FormGroup, FormArray, FormControl, FormBuilder } from '@angular/forms';

export interface Fruit {
  uid: string;
  name: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent   {
public checks = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}
];

myForm: FormGroup = this.initializeModelForm();

constructor(
  public _fb: FormBuilder
) { }

initializeModelForm(): FormGroup{
  return this._fb.group({
    otherControls: [''],
    myChoices: new FormArray([])
  })
}

onCheckChange(event) {
  console.log(event);
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
  if(event.target.checked){
    // Add a new control in the arrayForm
    formArray.push(new FormControl(event.target.value));
  }
  /* unselected */
  else{
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == event.target.value) {
        // Remove the unselected element from the arrayForm
        formArray.removeAt(i);
        return;
      }

      i++;
    });
  }
  console.log(formArray.value);
}
}

Answer №2

When considering an approach similar to Netanel Basal's, it is essential to modify the submit function for smoother operation. One way to achieve this is by structuring a Form with values such as:

{
  "otherControls": "",
  "myChoices": [
    false,
    true,
    false
  ]
}

Although the initial data may seem unattractive, the submit function can be adjusted to transform it into a more organized format:

submit(myForm) {
    if (myForm.valid) {
      const value = { ...myForm.value };
      value.myChoices = this.checks
        .filter((x, index) => myForm.value.myChoices[index])
        .map(x => x.value);
      this.result = value;
    }
  }

This modification will result in a cleaner output, like so:

{
  "otherControls": "",
  "myChoices": [
    "value2"
  ]
}

While the submit process may become slightly more complex, the form structure itself becomes streamlined and intuitive:

<form *ngIf="myForm" [formGroup]="myForm" (submit)="submit(myForm)">
  <div formArrayName="myChoices">
  <div *ngFor="let choice of myForm.get('myChoices').controls; let i=index" class="col-md-2">
    <label>
      <input type="checkbox" [formControlName]="i">
      {{checks[i].description}}
    </label>
  </div>
  </div>
  <button type="submit">submit</button>
</form>

This method eliminates the need for external functions and minimizes complications typically associated with dynamic forms. By setting up the form initially as:

initModelForm(): FormGroup {
    return this._fb.group({
      otherControls: [""],
      myChoices: new FormArray(this.checks.map(x => new FormControl(false)))
    });
  }

For further reference, see this StackBlitz demo

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

Is implementing client components in Server Side pages an effective strategy for optimizing SSR performance?

In order to overcome the challenge of using client-side components in server-side pages, I made the decision to create a client-side wrapper to encapsulate these components within server-side pages. This way, I can manage all API calls and data fetching on ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

Get tabular information in xlsx format by utilizing the xlsx npm package for download

I have been attempting to convert my json-like data into an xlsx file format. I utilized the xlsx npm package and followed various code samples available online, however, when trying to open the file in Excel, I encountered the following error: https://i.s ...

Javascript callback function cannot access variables from its parent function

As a Javascript newbie, I am currently diving into callbacks for my project. The goal is to retrieve address input from multiple text boxes on the HTML side and then execute core functionalities upon button click. There are N text boxes, each containing an ...

What is the best way to prevent an HTML form from being submitted when a user is not logged in, but still allow submission when the user is signed

One of the requirements for users of my application is to be signed in before they can submit form information. Upon clicking on the submit button, my jQuery script verifies if the user is already signed in. If the user is not signed in, an error message ...

"Encountering a module not found issue while trying to

Attempting to test out 3 node modules locally by updating their source locations in the package.json files. The modules in question are sdk, ng-widget-lib, and frontend. ng-widget-lib relies on sdk, while frontend depends on ng-widget-lib. To locally build ...

A guide on incorporating ng2-canvas-whiteboard into your Ionic 3 project

I'm trying to implement the npm package ng2-canvas-whiteboard into my Ionic 3 app. I followed all the instructions on the npm page and here is my package.json: "dependencies": { "@angular/common": "4.0.2", "@angular/compiler": "4.0.2", ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...

Set every attribute inside a Typescript interface as non-mandatory

I have defined an interface within my software: interface Asset { id: string; internal_id: string; usage: number; } This interface is a component of another interface named Post: interface Post { asset: Asset; } In addition, there is an interfa ...

Encountered issue #98123: Failed to generate development JavaScript bundle during `gatsby develop` using Webpack

To set up a new Gatsby starter blog, I executed the following commands: gatsby new blog https://github.com/alxshelepenok/gatsby-starter-lumen cd blog gatsby develop However, while running gatsby develop, I encountered numerous errors labeled as ERROR # ...

If the given response `resp` can be parsed as JSON, then the function `$

I was using this script to check if the server's response data is in JSON format: try { json = $.parseJSON(resp); } catch (error) { json = null; } if (json) { // } else { // } However, I noticed that it returns true when 'res ...

JavaScript and CSS tabs with smooth transition effect

I want to create tabs that smoothly fade between each other when switching. The code I have works, but there's a slight issue. When transitioning from one tab to the previous one, there is a momentary glitch where the last tab briefly changes state be ...

What is the best way to integrate react-final-form with material-ui-chip-input in a seamless manner

Currently, I am utilizing Material UI Chip Input wrapped with Field from react-final-form. The main objective is to restrict the number of "CHIPS" to a maximum of 5. Chips serve as concise elements representing inputs, attributes, or actions. For more ...

The unit test is running successfully on the local environment, but it is failing on Jenkins with the error code TS2339, stating that the property 'toBeTruthy' is not recognized on the type 'Assertion'

I've been tackling a project in Angular and recently encountered an issue. Running 'npm run test' locally shows that my tests are passing without any problems. it('should create', () => { expect(component).toBeTruthy();}); How ...

Target specifically the onhover div element using JQuery and trigger the smooth sliding down effect with the SlideDown() function

Is it possible to create a unique JQuery slidedown() function that will only be applied to the div where the mouse is hovering? I have managed to make it work by giving each div a separate class, but when I name them all the same, it triggers the slide do ...

identifiers that have been duplicated errors

My journey with VS 2017 and angular 2 started off smoothly, but I hit a roadblock when I encountered 352 errors upon restarting my machine. The errors were mostly "Duplicate Identifier errors," and after some investigation, I realized that I had the file i ...

Error: The URL constructor is unable to process /account as a valid URL address

Working on a new social media app using appwrite and nextjs, encountering an error "TypeError: URL constructor: /account is not a valid URL" upon loading the website. Here's the current file structure of my app: File Structure Below is the layout.tsx ...

Dynamic cell editing feature in PrimeNG table

Looking to implement the PrimeNG Table. https://i.stack.imgur.com/bQycr.png Check out the live demo on StackBlitz. The table has three editable columns. The "Property Name" column always displays a text box in edit mode, while the "Property Value Type" ...

Attempting to incorporate alert feedback into an Angular application

I am having trouble referencing the value entered in a popup input field for quantity. I have searched through the documentation but haven't found a solution yet. Below is the code snippet from my .ts file: async presentAlert() { const alert = awa ...