How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows.

I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is displayed and the table row checkboxes as well as the checkall box itself are not toggled.

However, I'm facing an issue where the checkAll box gets checked even when I return false. Could this be a problem with my binding?

HTML:

<input type="checkbox" name="checkAll" [(ngModel)]="checkedAll" (ngModelChange)="toggleAllEmployees($event)">

Component:

toggleAllEmployees(flag) {

    const temp = [];

    if (flag) {

        // Display error if selecting all employees exceeds maximum
        if (this.importResults.length > this.maxSelection) {

            /* Error message displayed here */
            alert('The number of employees selected (' + this.importResults.length + ') exceeds the maximum limit.');
            return false;

        } else {
            for (let i = 0; i < this.importResults.length; i++) {
                if (this.importResults[i].OnTempAssignment !== 'True') {
                    this.importResults[i].checked = true;
                    temp.push(this.importResults[i]);
                }
            }
            this.employeeSelection = temp;

            // Emit changes
            this.selectedEmployees.emit(this.employeeSelection);

        }
    } else {
        // Un-check all boxes
    }
}

Although none of the table row checkboxes get checked and the error is displayed correctly, the box I click on still toggles. I expected return false; to prevent this. Is there a flaw in my binding that enables it to toggle anyway?

Answer №1

ngModelChange event is triggered when the value bound to a checkbox changes, but it may be too late to prevent the toggle operation.

To effectively stop the checkbox from toggling, you should bind with the click event instead. You can then use $event.preventDefault() to halt the checkbox from being toggled.


You can even add some logic before calling $event.preventDefault() to determine whether the checkbox should indeed be prevented from changing its status.

Check out this Plunker demo.

Answer №2

HTML

 <input type="checkbox" [checked]="isChecked" (click)="onClick($event)">

Code

onClick(e){
  e.preventDefault();

 // When the user confirms, make an API call to update the checkbox value
 this.isChecked = true;
}

Answer №3

I encountered a similar issue where I needed to check if a limit had been reached before preventing the default behavior with preventDefault() and stopping event propagation with stopPropagation()

<input type="checkbox" class="message-checkbox mr-2" (click)="stopCheckingStates($event)"
                        (change)="stateChange(state, $event)" [checked]="isStateChecked(state.id)">

Next, in the TypeScript file:

    stopCheckingStates(event){
    this.stopCheckingCheckBox(event, 1);
  }

  stopCheckingCheckBox = (event, limit) => {
    if (selectArray.length > limit) {
      if (event.target.checked) {
        event.preventDefault();
        event.stopPropagation();
      } else {

      }

    }
  }

You can adjust the limit as needed, in my case it was set to one.

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

The data from the method in the Vue.js component is not displaying as expected

Currently diving into Vue.JS (2) and exploring the world of components. My current challenge involves using a component within another component, grabbing data from a data method. Here's what I have so far: HTML <div id="root"> <h1> ...

encountering a problem with iterating through a JSON array

After making an ajax call and retrieving select options in json format, I implemented the code below to display these new options in place of the existing ones: success: function (data){ var $select = $('#dettaglio'); $select.html(' ...

Is there a method to retrieve Mui state classes easily?

One thing I really appreciate is the way to style mui-components with their class names. I'm curious if there's a method to access state classes like Mui-checked using a variable. Let me delve deeper into this: I have a styled component that lo ...

How can you effectively utilize Selenium to web scrape a webpage featuring collapsible fields?

Have you checked out this website - ? I'm currently working on extracting fixture data from it, such as competition names, team names, and dates. Although I have a scraping solution in place, the challenge lies in dealing with collapsible competition ...

How to stop the previous page from reloading with Express.js routing?

Just starting out with express and web development in general, I have a question regarding routing. Currently, I am working on a web app using Firebase with pure JS and implementing routing on Firebase cloud functions. The routing logic is outlined below: ...

Storing repeated inputs in local storage multiple times

I am working on a feature where I need to store data in local storage multiple times using a dropdown menu and some input fields. Currently, I am able to retrieve all the values from the input fields and see them in the console log. My goal is to save thes ...

The error message "ngx-contextmenu - The function connectedTo() is not a valid function for this.overlay

I recently updated my angular version to 13 and also upgraded ngx-contextmenu to version 5.4.0. However, after the upgrade, I encountered an issue where the context menu was not visible and throwing an error as shown in this screenshot. To resolve the pr ...

Unexpected outcomes experienced with AJAX in ASP.NET due to javascript integration

I experimented with two methods (server and client side) for initiating a JavaScript AJAX call to post a ticket on a website and then retrieve a link containing the ticket number for tracking or editing purposes. However, both approaches yielded different ...

Error encountered: Attempting to render an object as a react component is invalid

I am attempting to query data from a Firestore database. My goal is to retrieve all the fields from the Missions collection that have the same ID as the field in Clients/1/Missions. Below, you can find the code for my query: However, when I tried to execu ...

I encountered an issue trying to locate the module '@angular/compiler-cli'

I've encountered an issue with my new project as it's not allowing me to run 'ng serve' due to the 'cannot find module @angular/compiler-cli' error. Despite trying to clear the cache and deleting the node_modules folder withi ...

Is it possible to determine if an HTML form has been modified?

Is there a way in typescript to determine if a form has been changed and return true or false accordingly? For example, if I have a first name field with the current value of "John" and then change it to "Johny", it should return true. But if I revert it b ...

Using AngularJS Scope to Map an Array within a JSON Array

I'm attempting to extract the type and url values from the media2 object within this JSON array and assign them to an AngularJS scope Array. "results":[ { "session2":[ { "__type":"Object", "abou ...

"Accessing your account only requires a simple two-click login process

Why do I need to click the log in button twice for data validation on my forum website? While designing a forum website, I noticed that users have to click the log-in button twice before the system validates and processes the input data. Below is the code ...

I encountered a warning while running the npm command. Can someone provide guidance on how to address this issue?

npm WARNING config key key and cert are no longer utilized for most registry functions. npm WARNING config Use registry scoped keyfile and certfile instead. npm WARNING config Example: npm WARNING config //another-registry.tld/:keyfile=/path/to/key ...

Replicate and modify the settings on a fresh radio inspection

In my approach, I am avoiding direct HTML editing and instead utilizing JavaScript/jQuery to accomplish the desired outcome. Initially, one input (specifically 'Express Shipping') is pre-selected by default. The goal is to clone/copy the HTML co ...

Invalid prop type: A form field received a `checked` prop without a corresponding `onChange` handler

In my project, I have a Parent Component called CandidateList and a Child Component called Candidate. The CandidateList component has a Select All checkbox that triggers a function to set the state when candidates are being selected, and then passes that s ...

Unable to successfully import Node, JS, or Electron library into Angular Typescript module despite numerous attempts

I'm still getting the hang of using stack overflow, so please forgive me if my question isn't formulated correctly. I've been doing a lot of research on both stack overflow and Google, but I can't seem to figure out how to import Electr ...

How can I ensure that a particular component type passes the typescript check in a react-typescript project?

I'm fairly new to using TypeScript, although I have a lot of experience with React (and prop-types). Recently, I've run into an issue when it comes to typing my components, specifically when another component is passed as a prop. I already have ...

Exploring Validations within Nested Forms in Angular

After grappling with this issue for a month, I am seeking any suggestions or advice. In my form pages, user input data is received. These pages include a component called basa-crud-page, which utilizes Template Driven Forms. The code snippets within this ...

Struggling with a TypeError in React/Next-js: Why is it saying "Cannot read properties of undefined" for 'id' when the object is clearly filled with data?

Encountering an issue with a checkbox list snippet in Next-js and React after moving it to the sandbox. Each time I click on a checkbox, I receive the error message: TypeError: Cannot read properties of undefined (reading 'id') This error is co ...