Count the number of checked checkboxes by looping through ngFor in Angular

My ngFor loop generates a series of checkboxes based on the X number of items in childrenList:

<div *ngFor="let child of childrenList; let indice=index">
    <p-checkbox label="{{child.firstname}} {{child.lastname}}" binary="true" (onChange)="dentalChanged(indice, $event)" name="item-{{indice}}">
    </p-checkbox>
</div>

I have successfully been able to detect when a checkbox is checked using the following code:

dentalChanged(indice: any, event: any): void {
  alert(indice)
  console.log(event.checked)
}

Now I am facing an issue where I need to save the selected items upon clicking a button. Since the number of elements in childrenList varies, I am unsure how to iterate through them from index 0 to n.

Your assistance is greatly appreciated.

Answer №1

One can implement SelectionModel to handle selection in Angular:

component

  selectedItems = new SelectionModel<any[]>(true, []);
  itemsToSelect = [{ name: "option1" }, { name: "option2" }, { name: "option3" }];

template

<div>
  <div *ngFor="let item of itemsToSelect">{{item.name}} - <mat-checkbox (change)="selectedItems.toggle(item)"
      [checked]="selectedItems.isSelected(item)">
    </mat-checkbox>
  </div>

  <div>
    Number of selections: {{ selectedItems.selected.length}}
  </div>
</div>

SelectionModel provides handy methods like toggle, deselect, isEmpty, clear, and more.

Answer №2

Save specific values in a variable for later use

selectedItems: any[];

dentalModified(index: any, event: any, child: any): void {
  if (event.checked) {
    this.selectedItems.push(child);
  } else {
    // If no unique identifier like id, you can also use splice and index to remove the child
    this.selectedItems = this.selectedItems.filter(c => c.id != child.id);
  }
}

Invoke dentalChanged method with the child parameter from HTML

<div *ngFor="let child of childrenList; let index=index">
    <p-checkbox label="{{child.firstname}} {{child.lastname}}" binary="true" (onChange)="dentalModified(index, $event, child)" name="item-{{index}}">
    </p-checkbox>
</div>

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

Creating an Angular 2 project with DevExtreme in Visual Studio 2017/2015: A step-by-step guide

I would appreciate some guidance on setting up an Angular 2 project with DevExtreme control using Visual Studio 2017/2015. Specifically, I am interested in utilizing the control demonstrated at . Your assistance would be greatly appreciated. ...

Guidance on showcasing the current day's weekday name through TypeScript

I am perplexed about how to begin in TypeScript after successfully setting up the display using gate. ...

Modifying Angular 4 instance field in the code does not update the template as expected

One issue I am encountering is that changes in the instance variable in my component class are not automatically reflected in my template file unless I explicitly call ref.detectChanges The method signInWithGoogle in my auth service is called from the com ...

Angular drag and drop functionality combined with interactive buttons for list management

Looking to create an Angular component for re-sorting objects by dragging from one list to another? I also need this component to include buttons for additional functionality. I've explored the various drag and drop components available on the Angula ...

Tips for ensuring old logs do not display on Heroku Logs

I'm puzzled as to why my heroku logs command keeps showing old logs. Attempting to resolve this issue, I tried: heroku drains heroku logs However, the logs still display outdated information: app[api]: Release v1 created by user <a href="/cdn-c ...

Creating a custom class to extend the Express.Session interface in TypeScript

I'm currently tackling a Typescript project that involves using npm packages. I am aiming to enhance the Express.Session interface with a new property. Here is an example Class: class Person { name: string; email: string; password: strin ...

Perform an action after the Ngx Bootstrap modal has been hidden

My modal features a login button: <button type="button" (click)="save()" class="btn btn-primary"> login </button> Upon clicking the button, my desired outcome is to: first hide the modal, and second navigate to another route. However, ...

Do you think it's wise to utilize React.Context for injecting UI components?

I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...

Issues with the functionality of Angular and Material's multi-level menu and breadcrumb integration

Currently, I am working on a project using Angular 6 and Angular Material 6. I am attempting to create a multilevel menu with breadcrumb functionality. While I have successfully implemented the multilevel menu, I am facing an issue with navigating the menu ...

The Angular 2 ngSubmit.emit() function does not update the submitted property of the <myform> form

Whenever I run the code, the addResult() method property is triggered but the submitted property always remains empty. Any thoughts on why this might be happening? <form class="form-horizontal" (ngSubmit)="addResult()" #resultForm="ngForm"> &l ...

Center align the mat-expansion-panel material component in a vertical orientation

When working with the mat-expansion-panel component alongside a mat-accordion, I've encountered an issue where the items are not aligning vertically at the center/middle. I'm unsure of the proper method to achieve vertical alignment for the conte ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

I keep receiving error code TS2339, stating that property 'total' is not recognized within type any[]

Check out this code snippet. Can you provide some assistance? responseArray: any[] = []; proResponseArray: any[] = []; clearArray(res: any[]): void {res.length = 0; this.response.total = 0; } handleSubmit(searchForm: FormGroup) { this.sho ...

The function record.factory does not exist

Here is the code for the AppComponent: import { Component, OnInit } from '@angular/core'; import { APICommunicationService } from './api-comm/api-communication.service'; import { Observer } from 'rxjs'; @Component({ sel ...

Looking to incorporate ReactiveFormsModule into an Angular custom library, but hitting roadblocks

I'm currently facing an issue with integrating reactive forms in my Angular custom library development. I decided to include @angular/forms as a peerDependency in the library's package.json manually, like so: { "name": "abc-library" "version": ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Troubleshooting a pair of distinct software programs: Angular and a web API

I am currently working on two separate applications, one developed in Angular and the other in web API. There is a function in my Angular application that calls a method in .NET Core. I would like to know if it is possible to debug the Angular function and ...

troubleshooting angular universal with HTTPS

My angular universal app is all set up and running smoothly for POST requests on the server-side using localhost to pre-render my app. An example of a working URL would be http://localhost:8000/api/get-info. However, things took a turn when I deployed the ...

Uploading images using the power of Angular and Node.js

I have been struggling with a persistent issue for quite some time now, and I have not been able to find a solution anywhere. My goal is to allow users to update their avatars on their profiles. However, every time I attempt to pass the file to my node ser ...

Leveraging both the spread operator and optional fields can improve the productivity and readability of your

Imagine you have an object with a mandatory field that cannot be null: interface MyTypeMandatory { value: number; } Now, you want to update this object using fields from another object, but this time with an optional field: interface MyTypeOptional ...