A Guide to Linking Checked Boxes to Form Arrays with FormBuilder in Angular

Currently, I am dealing with a collection of checkboxes and utilizing Angular's FormBuilder to handle my form. My objective is to link the values of the selected checkboxes to a form control named itemIds within my form group.

      constructor(private formBuilder: UntypedFormBuilder
        ) {
      }
    serviceTaskForm = this.formBuilder.group({
    ....
     itemIds : ['']
    })
  onCheckboxChange($event: MatLegacyCheckboxChange) {

  }

Regarding my HTML code:

  <form>
.....
      <mat-form-field appearance="fill">
        <div class="demo-select-all-checkboxes" *ngFor="let task of tasks">
          <mat-checkbox
            (change)="onCheckboxChange($event)"
            [value]="task.itemId">
            {{ previousTask.itemId }} {{ previousTask.invoice}} 
          </mat-checkbox>
        </div>
      </mat-form-field>
    </form>

https://i.sstatic.net/GPIIZR7Q.png

I am aiming for the itemIds form control to be an array that includes all the selected checkbox values. Any insights on how I can achieve this?

Answer №1

  1. Ensure that your control for itemIds is a form control with an array value.

  2. To set up the itemIds form control, utilize the setValue() or patchValue method to provide an array value.

  3. If you are dealing with multiple checkboxes using a form control, implement the following:

    • Create a method called onCheckBoxChange to toggle the checkbox selection in the array based on the event (checked/unchecked).
    • Implement a method named isChecked to verify if the itemId is checked.
import {
  MatCheckboxModule,
  MatCheckboxChange,
} from '@angular/material/checkbox';

serviceTaskForm = this.formBuilder.group({
  itemIds: [[]],
});

ngOnInit() {
  this.itemIdFormControl.patchValue([1]);
}

onCheckboxChange($event: MatCheckboxChange, itemId: number) {
  let value: number[] = this.itemIdFormControl.value;

  if ($event.checked) value.push(itemId);
  else value.splice(value.indexOf(itemId), 1);

  this.itemIdFormControl.setValue(value, {
    emitEvent: false,
  });
}

isChecked(itemId: number) {
  return this.itemIdFormControl.value.indexOf(itemId) > -1;
}

get itemIdFormControl() {
  return this.serviceTaskForm.controls['itemIds'];
}

For displaying in your view:

  1. Avoid nesting the <mat-checkbox> inside the <mat-form-field>. Remove the <mat-form-field> element. Reference: Angular material Error when mat-checkbox is imported

  2. Use the [checked] attribute instead of the [value] attribute.

<ng-container class="demo-select-all-checkboxes" *ngFor="let task of tasks">
  <mat-checkbox
    (change)="onCheckboxChange($event, task.itemId)"
    [checked]="isChecked(task.itemId)"
  >
    {{ task.itemId }} {{ task.invoice }}
  </mat-checkbox>
</ng-container>

Check out the Demo on StackBlitz

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 to set focus on an input element in Angular 2/5

After clicking, the input element is displayed (it is initially hidden). I want this input to be in focus when it appears. This functionality works well when the input is not hidden by *ngIf (#inputElement2). Is there a way to achieve the same for #inputE ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

Localization of Dates in Angular applications

I'm facing an issue in my Angular 8 application where I can't seem to properly display date fields in a localized format. I would like to achieve the following formatting: In English: "February 18, 2020 12:15:50" In French: "18 février 2020, 1 ...

Generating HTML content using Angular 8 and JSON data

Currently, I am managing an Angular Storybook that consists of various components. Within the stories.ts file of a component, there is a JSON snippet containing properties such as the content of a DIV element, shown below... { "accordionLink": ' ...

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

FabricJS Canvas with a React DropDown Feature

While I have successfully created a TextBox on FabricJS Canvas, creating a Dropdown component has proven to be a challenge. The fabric.Textbox method allows for easy creation of text boxes, but no such built-in method exists for dropdowns in FabricJS. If y ...

Transferring an Image File from Angular 8 to a Spring Boot Application

Having trouble sending a file from my Angular 8 app to my Spring Boot server. I've tried using MultiPartFile and HttpServletRequest in Spring, among other methods, with no luck. I'm hoping someone can provide guidance on how to successfully retr ...

The supplied parameters do not correspond with any valid call target signature for the HTTP delete operation

I've been attempting to utilize the http delete method in Angular 2, but I keep encountering a typescript error: Supplied parameters do not match any signature of call target.. Below is the code I am using: let headers= new Headers(); ...

Disabling the Angular router link

I'm currently working on an Angular application that utilizes routing and auth guards. Check out the code on StackBlitz View the app component HTML here <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-10 ...

Why are traditional Angular dependencies still necessary even when typedefinitions are being used?

I am currently in the process of transitioning my Angular 1.5 project to use TypeScript. The project is compiled with webpack and even though I have included Angular type definitions in my package.json file as shown below, "@types/angular": "~1.5.19", "@t ...

Tips for obtaining results from a File Reader

I am currently facing an issue with an onchange event in my HTML. The event is intended to retrieve an image from the user, convert it to a data URL, and then send it over socket.io to store in the database. However, I am struggling to figure out how to ac ...

Contrasts between importing libraries in angular.json vs. within a component

When trying to import jQuery into my Angular 7 application, I discovered that there are two different methods to accomplish this task. The first method involves adding the jquery.min.js file to the scripts property in the angular.json file. Alternatively ...

Missing 'id' property in object {`id`} when utilizing GraphQL with Typescript

As a newcomer to coding and Typescript, I apologize for my limited knowledge. I am currently facing an issue where my application is unable to communicate with my API due to an error caused by the primary id key having a "?" symbol, like so: export interfa ...

Angular2 - how can I effectively organize the logic between my components and services?

Within my current project setup, I have the following structure implemented: I have a Component that interacts with a Service Class which in turn calls an external API. The specific logic that I need to implement is related solely to the user interface. ...

"An error in the signature index results in the failure of the

I'm encountering a coding issue that's puzzling me. The TypeScript index signature I included in my code is as follows: const ships: { [index: string]: Ship } = {}; This snippet of code contains the problematic line: recieveAttack(e: any) { ...

Include a control within a form based on the Observable response

I am looking to enhance my form by adding a control of array type, but I need to wait for the return of an Observable before mapping the values and integrating them into the form. The issue with the current code is that it inserts an empty array control e ...

Is it necessary to include the file name in the path when uploading a file to a network server from the intranet?

While using a REST tool to upload a file from the intranet to a network server, I encountered an error message: "Access to the path '\\\servername.com\subfolder1\subfolder2\file_name' is denied" I am wondering if t ...

Is SASS stylesheet supported by the Angular 2 Ahead-of-Time compiler?

Considering giving Angular 2 Ahead-of-Time compilation another shot. I'll have to do some significant refactoring since my current custom build process will need to be reworked. Prior to diving in, I'm curious: if I reference external .scss fil ...

How to locate a specific object by its ID within a JSON structure embedded in an HTML template

I am currently working on the page where I display posts. Within my controller, I have: export class PostsComponent implements OnInit { posts$: Object; users$: Object; constructor(private data: DataService) { } ngOnInit() { this.data.getPo ...

FilterService of PrimeNg

Looking for assistance with customizing a property of the p-columnFilter component. I have managed to modify the filter modes and customize the names, but I am having trouble with the no-filter option. Has anyone found a solution for this? this.matchMo ...