The issue is that only the first checkbox within ngFor is being toggled on and off each time a different checkbox is clicked

When I have checkboxes inside a ngFor loop and click on any one of them, only the first one gets checked and unchecked, updating only the status of the first checkbox.

Here is the HTML template:

<div *ngFor="let num of count" class="m-b-20"> 
    <div class="checkbox"> 
        <input type="checkbox" id="check" name="num.value" value="num.checked" [(ngModel)]="num.checked" (click)="clicked(num)" ngDefaultControl/> 
        <label for="check"></label> 
    </div>
    {{num.checked}} 
</div>

Answer №1

Make sure to verify the value of name, as you have used a different name for each element: num.value. To ensure proper functionality, these should be consistent:

<div *ngFor="let num of count" class="m-b-20">
    <div class="checkbox"> <input type="checkbox" name="checkbox-list" [(ngModel)]="num.checked" (click)="clicked(num)" ngDefaultControl/> 
    <label for="check"></label> </div>{{num.checked}}
</div>

Remember that "checkbox-list" is now the designated name.

Answer №2

It appears that the issue may be due to having identical names for the checkboxes. When iterating, please ensure that each checkbox has a unique name assigned to it in order to resolve the problem.

Answer №3

To start, make sure to eliminate both the id and value attributes from your code.

<div *ngFor="let num of count" class="m-b-20">
<div class="checkbox"> <input type="checkbox" name="checkbox-list" [(ngModel)]="num.checked" [checked]="num.checked==true" (click)="clicked(num)" ngDefaultControl/> 
<label for="check"></label> </div>{{num.checked}}

It is unnecessary to include this attribute when using [(ngModel)] in a checkbox. Verify that it functions properly without it.

Answer №4

I encountered a similar issue while working with Angular 6 and Bootstrap 4. The problem was that when I clicked on the label, it didn't check the checkbox. However, clicking directly on the checkbox would work fine.

Below is the solution I implemented to fix this issue for future reference.

<ng-container *ngFor="let item of items">
     <div class="col-5 col-sm-5">
      <div class="form-group form-check">

        <!-- wrap the label around the checkbox -->
        <label class="form-check-label">
          <input type="checkbox" class="form-check-input" name="item_check" id="check_{{item.ID}}">
           {{item.name}}
        </label>
    </div>
   </div>
</ng-container>     

As you can see from the code snippet, wrapping the checkbox inside the label resolved the issue effectively.

Answer №5

Assign the id to the input tag, and reference it in the label tag.

<div *ngFor="let num of count" class="m-b-20">
  <div class="checkbox">
    <input type="checkbox" name="checkbox-list" [id]="num.value" (click)="clicked(num)" ngDefaultControl/>
    <label [for]="num.value"></label>
  </div>
  {{num.checked}}
</div>

Answer №6

The issue arises from the fact that all rows share the same id. To resolve this, consider adding a unique identifier to each row and column.

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

Optimizing Angular.js templates for faster loading using Node.js pre-compilation

As I delve into learning Angular and integrating it with my current Node.js framework, I find myself facing some challenges. Previously, I utilized Handlebars.js as my templating engine in Node.js, where I would build the context on the server side and the ...

Automate logging in and out of Gmail chat by programmatically simulating clicks on the span elements that represent the chat status in Gmail

When I'm at work, I prefer using Gmail's encrypted chat feature because it logs chats without saving anything to the hard drive. However, when I'm at home, I switch to Pidgin as logging into Gmail chat at home can lead to messages ending up ...

Switching up the image using a dropdown selection menu

I am struggling with updating an image based on the selection made in a dropdown menu. I am quite new to javascript, so I believe there might be a simple issue that I am overlooking. Here is my attempt at doing this: JS: <script type="text/javascript" ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

Constructing Browserify with dependencies containing require statements within a try-catch block

When attempting to integrate timbre.js (npm version) with Browserify, I encountered an issue where require statements for optional dependencies were enclosed in a try statement (check the source here). This resulted in a browserify build error displaying: ...

Error encountered in Google's Structured Data Testing Tool

<script type="application/ld+json"> {"@context" : "http://schema.org", "@type" : "LocalBusiness", "name" : "mywebsite.com", "description": "Lorem ipsum dolor sit amet", "image" : "http://mywebsite.com/image.jpg", "telephone" : "987654321", ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

Obtain the non-dynamic route parameters as query parameters in Next.js

I need help figuring out how to extract specific query parameters from a URL in my component. I want to exclude dynamic route parameters, such as {modelId}. For example, if the URL is /model/123456?page=2&sort=column&column=value, I only want to re ...

What is the best way to combine a QR code and an existing image using Java script?

Looking for help in embedding a created QR code into an existing image. I am proficient in nodeJS, JavaScript, and jQuery. Any assistance would be greatly appreciated. ...

Using HTML5 input pattern to permit the use of a comma separator when entering thousands

I'm currently working on creating a regular expression for an HTML5 input form that allows the comma as a separator for thousands. Here are some examples of valid input: 20 3000 4,000 600000 7,000,000 8000000 The requirements for the input are: o ...

Ensuring the text remains positioned above another element constantly

Looking to have the text float above a regular box and resize the font size accordingly? Here's what I've tried: https://jsfiddle.net/a87uo3t2/ @import url('https://fonts.googleapis.com/css?family=Share+Tech+Mono'); body { margin: ...

Adjusting the maxContentLength and maxBodyLength values in Axios

While utilizing the "Axios" library to invoke a WCF method with file information and content as parameters, I encountered an issue. The file is read and transmitted as a base64 encoded string. However, when the file size surpasses a specific limit, Axios t ...

"Error in Visual Studio: Identical global identifier found in Typescript code

I'm in the process of setting up a visual studio solution using angular 2. Initially, I'm creating the basic program outlined in this tutorial: https://angular.io/docs/ts/latest/guide/setup.html These are the three TS files that have been genera ...

Invoking a function in an Angular 4 component using a <td> element

Take a look at this block of code: personListComponent.html <tr *ngFor="let person of personService.getPersons()"> <td (onShow)="getCountry(person)">{{person.name}}</td> <td>{{country}} </tr personListComponent.ts ...

Can anyone suggest a more efficient method for implementing jQuery toggle?

Summary: I have a customized javascript calendar that offers different viewing options such as day, week, and month. These views display events with specific class names. My current challenge is finding an effective method to toggle the visibility of thes ...

There is no XHR request sent when invoking the http function

I am facing challenges in configuring a service in angular2 to interact with a REST backend. My attempt at setting up a basic example for sending requests to a rest backend and handling the response seems to be on track. The Service is being called correc ...

What is the best way to align the content of a <ul> in the center while keeping the text left-aligned and setting a max-width

UPDATE: Including an image for better visualization: [![Check out the image link][1]][1] To understand more clearly, refer to this fiddle: https://jsfiddle.net/c7jazc9z/2/ Currently, I have a list with items aligned to the left. The goal is to center th ...

Can APP_INITIALIZER function within lazy loaded modules in Angular?

I recently implemented a lazy loaded module in my application and tried to add APP_INITIALIZER but unfortunately, it doesn't seem to be triggering. Surprisingly, the syntax I used is identical to that of my main app where it works perfectly fine. Can ...

What is the best way to use @foreach to make the text in the final row of a table bold?

Is there a way to apply bold styling to the text in the final row using @foreach in HTML? I am looking to emphasize the total sum of each column by displaying it in bold text. While I initially considered creating a new table below the current one solely ...

Merge adjacent CSS blocks seamlessly without the need for JavaScript

I am facing an issue with styling div elements that have editable content through a WYSIWYG inline editor on my website. Users often do not understand the importance of enclosing similar blocks of code in containing DIVs for proper formatting, resulting in ...