How do I select all checkboxes in TypeScript when I only click on one of them?

I'm currently working with a list of checkboxes in my HTML code:

<div class="col-sm-12" *ngIf="ControllerModel">
  <div *ngFor="let controller of ControllerModel" class="panel col-md-6 col-lg-6 col-xs-6">
    <div class="panel-heading">
      <span>
          {{controller.controllerDisplayName}}
      </span>

    </div>
    <div class="panel-body">
      <div *ngFor="let action of controller.actionsVM" class="col-auto my-1">
        <div class="custom-control custom-checkbox mr-sm-2">
          <input type="checkbox" class="custom-control-input"  id="customControlAutosizing">
          <label class="custom-control-label"  for="customControlAutosizing">{{action.displayName}}</label>
        </div>
      </div>
    </div>
  </div>
</div>

However, I'm encountering an issue where selecting one checkbox results in all checkboxes being selected.

What could be causing this problem? How can I go about resolving it?

Edit

To see the issue in action, click on the labels a1, a2, or a3. Sample

Answer №1

Implement ngModel for the checkbox input element

<input type="checkbox" class="custom-control-input" id="customControlAutosizing" [(ngModel)]="data.checkboxValue">

Answer №2

After reviewing the stackblitz linked in your post, it appears that you are attempting to bind the checked state to a text field (action.name). This will result in all checkboxes being ticked due to its truthy nature. Instead, consider adding a boolean field to your ActionModel to properly bind the checked state:

export interface Actionmodel {
    displayName:string;
    name:string;
    isChecked:boolean; // Make sure to add this boolean field
    metaData:string;
}

Next, use ngModel to bind the checked state to your model:

<input type="checkbox" class="custom-control-input" id="customControlAutosizing" [(ngModel)]="action.isChecked">

Ensure to initialize the isChecked field with false value, for example:

...
{
  displayName: "a1",
  name: "a1",
  isChecked: false,
  metaData: "a1",
}
...

The issue with the labels currently is that they all reference the same id, leading to confusion. To resolve this, use the index in ngFor to create unique ids within the div:

<div *ngFor="let action of controller.actionsVM; let i = index" class="col-auto my-1">
  <div class="custom-control custom-checkbox mr-sm-2">
    <input type="checkbox" class="custom-control-input" id="{{'customControlAutosizing' + controller.controllerName + i}}" [(ngModel)]="action.isChecked">
    <label class="custom-control-label" for="{{'customControlAutosizing' + controller.controllerName + i}}">{{action.displayName}}</label>
  </div>
</div>

EDIT: considering you have two checkbox divs, ensure to append controller.controllerName + i to the input ids

Feel free to check out the live demo here: 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

Swap out AJAX following a successful retrieval and when managing errors

I currently have a basic AJAX load function set up to load a specific URL: <div id="load"> <h1 id="status">Loading...</h1> </div> <script type="text/javascript"> $(document).ready(function(){ $.ajaxSetup({cache: false}); var ...

Ways to display and conceal menu depending on initial view and scrolling

On my website, I have implemented two menus - one to be displayed when the page loads and another to show up when a scroll occurs. You can view my page here. The goal is to have the white part visible when the position is at the top, and switch to the blu ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

Angular does not adhere to globally defined styles

I have defined the margins for mat-expansion-panel in my styles.css file as follows: mat-expansion-panel { margin: 2vh; } Unfortunately, these margins will not be applied to my components unless they are also specified in the local CSS file. Even try ...

What are the benefits of initializing my Angular2 reactive form in the constructor instead of ngOnInit?

According to several responses, it is recommended to initiate the initial functions of an Angular2 application within the ngOnInit() method, reserving the constructor specifically for dependency injection tasks. However, the Reactive Forms tutorial I am c ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

Developing web applications using a combination of PHP, MySQL, and

I am in need of creating an HTML form that functions as CRUD. This form should be able to record inputs such as "row_number", "channel_name", and "ip_address". It will store all the data in a MySQL table using the "ORDER BY row_number" function. The form i ...

Send the data to be placed in the div to launch the window

I'm attempting to open a new window within the same tab and transfer some html code to be inserted into a specific div section of the newly opened window. However, I'm encountering difficulties in passing the data as illustrated below: JavaScrip ...

Building a custom DSL expression parser and rule engine

In the process of developing an app, I have included a unique feature that involves embedding expressions/rules within a configuration yaml file. For instance, users will be able to reference a variable defined in the yaml file using ${variables.name == &a ...

Error encountered during Jasmine unit testing for the ng-redux @select directive

Here is a snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { select } from 'ng2-redux'; import { Observable } from 'rxjs/Observable'; import { PersonalDetailsComponent } from ' ...

Avoid altering the Vuex store state directly without using mutation handlers in VueJS

I am currently working on developing a listenAuth function that monitors the "onAuthStateChanged" event in firebase to inform the vuex store whenever a user logs in or out. From what I can gather, I am only updating state.authData using the mutation handle ...

Tips for verifying that parameters possess designated characteristics in TypeScript

How can I ensure that data2 and data3 work correctly, while data1 triggers an error if the data type is not specified as shown in the code below? I need to validate that when a user enters params like {name: 'aa', age: 20}, it should throw an er ...

Reactjs error: Invariant Violation - Two different nodes with the matching `data-reactid` of .0.5

I recently encountered a problem while working with Reactjs and the "contentEditable" or "edit" mode of html5. <div contenteditable="true"> <p data-reactid=".0.5">Reactjs</p> </div> Whenever I press Enter or Shift Enter to create ...

SoundCloud and Vimeo have the capability to link their players across separate tabs, and even between tabs and embedded players

I find it intriguing how SoundCloud and Vimeo are synchronized with their tabs, so that when you play something in one tab, the others pause. It's worth noting that this feature only works on SoundCloud when two instances of the website are open, wher ...

Implementing conditional validation in Formik on cancel button click in a React application

When defocusing from the field without entering any data, a validation error occurs. Similarly, if you click on the submit button without giving a value, a validation error is triggered - this behavior is expected. However, how can we prevent the validat ...

The error message is stating that the module located at C://.. does not have an exported member named "firebaseObservable"

Trying to follow an Angular/Firebase tutorial for a class but encountering issues. The FirebaseListObservable is not being imported in my component even though I have followed the tutorial closely. I've looked at similar questions for solutions but ha ...

Is it possible to switch the hamburger menu button to an X icon upon clicking in Vue 3 with the help of PrimeVue?

When the Menubar component is used, the hamburger menu automatically appears when resizing the browser window. However, I want to change the icon from pi-bars to pi-times when that button is clicked. Is there a way to achieve this? I am uncertain of how t ...

Looking to include a data-* attribute within a div element for the utilization of a third-party JavaScript library like React or Next.js?

let speed = '{ "speed": 0.2 }'; <div className="section jarallax h-100vh" data-jarallax={speed} style={{backgroundImage: "url('/images/header-bg.jpg')"}} id="home"> </div> <Script src="./js/parallax.js" strate ...

Importing usernames and passwords from a .txt file with Javascript

I'm in the process of creating a website that includes a login feature. The usernames and passwords are currently stored within the website files as .txt documents. I am aware that this method is not secure, but for the purpose of this project, I want ...

Is it possible to configure the Eclipse Javascript formatter to comply with JSLint standards?

I'm having trouble setting up the Eclipse Javascript formatting options to avoid generating markup that JSLint complains about, particularly with whitespace settings when the "tolerate sloppy whitespace" option is not enabled on JSLint. Is it possible ...