Angular2: Determining which checkboxes have been selected

Currently, I am utilizing angular2 and have the following HTML code:

<div *ngFor="let val of channelForTabs; let i=index">
            <label for="isCheckBox" style="margin-left:15px;">Draw</label>
            <input id="checkBox{{i}}" type="checkbox" class="fitCheckbox" style="margin-left: 10px;width: 16px;" />
            <de-series-prop></de-series-prop>
        </div>

With each value in channelForTabs, a checkbox and series component are added. How can I determine which checkboxes are checked without using the (change) method?

On a button click, I would like to identify which checkboxes are checked and retrieve the corresponding series data.

Answer №1

To implement functionality using ngModel and ngModelChange event, follow the code snippet below:

<input type="checkbox" (ngModelChange)="onCheckboxChange(color, $event)" checked="false" [ngModel]="!color"> {{color}}<br>

Define your method like this:

 onCheckboxChange(value, event){
    if(event){
    this.selectedItems.push(value);
    }
    console.log(value);
  }

Check out the LIVE DEMO

Answer №2

While this method may function, when a user deselects an option, the value remains in the array. To ensure accurate results, the value should be removed each time it is unchecked.

let idx = this.selectedItems.indexOf(element.value);
            this.selectedItems.splice(idx, 1);

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

"This error message states that the use of an import statement outside a module is not allowed

After searching for a solution without any luck, I decided to start a new discussion on this topic. Currently, I am working on azure functions using Typescript and encountering the following error: import { Entity, BaseEntity, PrimaryColumn, Column, Many ...

Issue detected in Angular 2 Heroes Tutorial: The element with the selector "my-app" was not found in the document

Currently, I am in the process of following along with the Heroes tutorial on the official angular website. The project was created using CLI and everything seemed to be working smoothly up until Part 6 on Routing: https://angular.io/tutorial/toh-pt5 In ...

After defining the NEXTAUTH_URL and NEXTAUTH_SECRET variables, the getServerSession(authOptions) function in NextJS is returning null

I've been attempting to set up OAuth with the Google provider for my Next.js 13 web application. Unfortunately, I'm encountering an issue where getServerSession(authOptions) is returning null. Despite trying various solutions such as setting NEXT ...

What could be the reason for the discrepancy between my get_token() function and the value obtained from request.META.get("CSRF_COOKIE")?

Can anyone shed light on why I'm facing this particular issue? I am currently exploring the integration of Angular 17 as a Frontend with Django as a Backend. While validating a form, I encountered an issue where the token obtained from Django does no ...

How can a method be called from a sibling component in Angular when it is bound through the <router-outlet>?

In my current project, I have implemented an application that utilizes HTTP calls to retrieve data from an API endpoint and then displays it on the screen. This app serves as a basic ToDo list where users can add items, view all items, delete items, and pe ...

Experience the convenience of lazy-loading in Angular Ivy: The InjectionToken ng-select-selection-model provider is not available

Issue Description I have integrated angular's IVY compiler and lazy-loading feature according to the tutorial found here: However, when I attempt to lazy-load a module and add an instance of a component to my application, the ng-select element is not ...

What is the best way to incorporate node_module during the iOS build process in Ionic 2?

Looking to implement an autosize module for automatic resizing of an ion-textarea. Module: Following the installation instructions, I tested it in the browser (ionic serve) and on my iPhone (ionic build ios => run with xcode). Browser: The module wor ...

Encountering a glitch when attempting to run Bootstrap 4 on an Angular 6 Application

After installing Bootstrap 4 using Angular CLI, I encountered an error when running the application. To resolve this issue, I made changes to the angular.json file: "styles": [ "src/styles.css", "../node_modules/bootstrap/dist/css/bo ...

Retrieve the non-empty attributes of a JSON object

I have a function in Typescript that extracts specific values from a JSON data object, some of which may be empty. How can I retrieve only certain data fields? Here is the function: let datosCod; for (let get in Object.keys(transfConsData)) { co ...

Sending a parameter to a route guard

I've been developing an application that involves multiple roles, each requiring its own guard to restrict access to various parts of the app. While I know it's possible to create separate guard classes for each role, I'm hoping to find a mo ...

What is the process for implementing angular-material's pre-defined theme variables in component styling?

I was trying to create a more dynamic background-color for my .active class within my mat-list-item Here is the HTML: <mat-list-item *ngFor="let page of pages" matRipple routerLinkActive="active" > < ...

Learn how to incorporate the dynamic array index value into an Angular HTML page

Exploring Angular and facing a challenge with adding dynamic array index values in an HTML page. Despite trying different solutions, the answer remains elusive, as no errors are being thrown. In TypeScript, I've initialized an array named `months` wh ...

Contrasting covariant and contravariant positions within Typescript

I'm currently diving into the examples provided in the Typescript advanced types handbook to broaden my understanding. According to the explanation: The next example showcases how having multiple potential values for the same type variable in co-var ...

When someone visits a site using Next.js, the redirect feature may successfully load the site, but it fails to actually

I have a serverless logout function in Next.js: import magic from './magic'; import { withSessionRoute } from './sessions'; export default withSessionRoute(async function logoutHandler( request, response, ) { try { if (reques ...

Set certain properties within the nested object to be optional

Within a TypeScript project, there exists a type definition that looks like this: type Bar = { x: string; y: string; data: { z: string; w: string; }; }; This type is imported and widely used throughout the project, making it impossible for ...

Guide to implementing validation in an angular 2 dropdown using the Model-driven Approach

When the user clicks the submit button, the dropdown validation does not occur. I want the form to be validated if the user does not select any value, and in that case, the form state should be invalid. In my scenario, I have disabled the submit button whe ...

Access Denied: Origin not allowed

Server Error: Access to XMLHttpRequest at '' from origin 'http://localhost:4200' has been blocked by CORS policy. The 'Access-Control-Allow-Origin' header is missing on the requested resource. import { Injectable } from &apo ...

Broadcast the latest N occurrences

I am working on an Angular 6 application where I want to display the most recent N events from a continuous stream of events coming from a web-socket. Currently, the data is shown using RxJS Observable<Event[]>: <div *ngFor="let event of (wsEven ...

Guide to making a Material Design Radial effect animation

I am looking to create a unique toolbar effect by following the material design radial reaction choreography guideline. https://i.stack.imgur.com/6oB8r.gif I want to achieve this using an angular 2 transition, but I need some guidance on how to implement ...

Error in zone: 140 - Property 'remove' is not readable

I'm brand new to kendo ui. I successfully set up a prototype in my fiddle with a working delete confirmation window. However, when I try to integrate it into my existing codebase, I encounter an error: Cannot read property 'remove' at the li ...