What is the best way to limit the selection of checkboxes based on specific conditions?

Using ngModel in Angular 5, I have the following Html:

<span *ngFor="let id of Ids">
  <input class="checkbox" type="checkbox" [(ngModel)]="strManyModel[id]"   (change)="setValue($event)" [value]="id">
 </span>

And here is the corresponding TypeScript:

setValue(e){
   if(selectedChkBox > 5){
    this.strManyModel[e.target.value] = false;
  }
}

I am trying to limit the number of checkboxes that can be selected to 5. Currently, once 5 are selected, any additional selections are allowed. However, I want to restrict checkbox selection after 5 have been checked. Users should only be able to select up to 5 checkboxes at a time. If they try to check another one after selecting 5, they must first uncheck one of their previous selections.

Answer №1

To add another class property, you can create a new one called:

public maxAllowedCheckboxes = 5;

Next, implement the following function:

public isCheckboxDisabled(): boolean {
  return Ids.length >= this.maxAllowedCheckboxes;
}

Finally, include the following template code:

<input class="checkbox" [disabled]="isCheckboxDisabled()" type="checkbox" [(ngModel)]="strManyModel[id]" (change)="setValue($event, i)" [value]="id">

Answer №2

If I'm understanding correctly, you're looking to deactivate other checkboxes when 5 are selected and keep the unchecked ones disabled until the number of checked boxes is less than 5...

One way to achieve this is by storing objects in an array with a checked property to monitor their state. Additionally, introduce a new boolean variable and a "counter" to track the number of checked checkboxes. Disable the unchecked checkboxes and once the maximum of 5 checkboxes have been chosen:

<div *ngFor="let chk of checkBox; let i = index">
  <input [(ngModel)]="chk.checked" 
         type="checkbox" 
         [disabled]="!chk.checked && maxNo" 
         (change)="onChange($event.target.checked)">{{chk.name}}
</div>

The array should contain objects with a name and checked property. The change event will increment or decrement based on the checked checkboxes and toggle the boolean flag maxNo:

onChange(isChecked: boolean) {
  isChecked ? this.amt++ : this.amt--;
  this.maxNo = this.amt === 5 ? true : false;
}

Check out this StackBlitz for reference.

Answer №3

One potential solution could look like this:

 <div *ngFor="let itemId of itemIds; index as ind">
  <input class="checkbox" type="checkbox" [(ngModel)]="selectedItems[itemId]" (change)="updateValue($event, ind)" [value]="itemId">
</div>

updateValue(event, index){
  if(itemIds.length >= 5){
    selectedItems[index] = false;
  }
}

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

Retrieve Gridview properties using JavaScript

I need to adjust the font size of my gridview using JavaScript to make it more suitable for printing. What is the best way to change the font size specifically for a gridview using JavaScript? ...

Automatically Modify Uploaded Files on the Server

There is one thing that has caught my attention. I am interested in working with scripts that can automatically edit a file once it's been uploaded. For example, imagine having a form where someone uploads an HTML file. The script would then edit spe ...

Navigate through each element with a specific class name in a block of HTML code using

Currently, I am dealing with an HTML string that is being retrieved through AJAX. Let's assume it looks like this: var htmlString = '<div class="post"></div><div class="post"></div>'; I want to find a way to iterat ...

Setting breakpoints in Node-Inspector can be quite challenging

After successfully setting up a web application, I decided it was time to learn how to properly debug it without relying on console.log. To start, I ran Node-Inspector via node-debug server.js (the main script file) and attempted to set up a breakpoint wit ...

Why isn't the ag-grid appearing within the function?

As a newcomer to using agGrid, please excuse any mistakes I may make. Previously, I worked with Kendo Grid on AngularJS, but we decided to switch to a different grid, so we're currently exploring agGrid. Below is a sample of agGrid that is functionin ...

The TypeScript compiler encounters difficulties in locating type definitions when utilizing an inherited tsconfig file

There seems to be an issue with the functionality of tsconfig.json inheritance, specifically regarding the proper inheritance of the "typeRoots" setting. http://www.typescriptlang.org/docs/handbook/tsconfig-json.html (folder structure provided below) we ...

Using Leaflet to set the view based on a GeoJSON dataset

I am working on incorporating a leaflet.js map with a square shape imported from an external GeoJSON file. I have determined the exact coordinates for the center of the square, and now I need to convert these coordinates in order to pass them correctly t ...

Showing Chosen Option: Angular 2 Integrated with Bootstrap Selection

HTML: <select formControlName="state" class="form-control" id="state" <option *ngFor="let state of stateList"> {{state}} </option> </select> Typescript: this.stateList = ['AK', 'TX', 'OR'] / ...

Design a dynamic top navigation bar in Angular or any other framework that automatically adjusts to the size of the screen, similar to the responsive bookmarks bar in

Could you offer guidance or suggestions on how to design a navigation bar (using Angular 1, jQuery, CSS, etc) that emulates the functionality of Google Chrome bookmarks bar when resizing the page? Essentially, as the page size decreases, a new button/symbo ...

Improper Ordering of Dependencies in RequireJS

Within my JavaScript file named Subcategories.js, there is a variable that I have defined. It looks something like this (though it's actually much larger): define({ subcategories: { "Category1": [ "Subcategory1-1", " ...

Utilize the error message as a label following the submission of the form

I need to implement a password reset form for user authentication purposes. Below is the HTML code: <form class="grid-wrapper" #f="ngForm" *ngIf="stepOne"> <div class="form-group first-row"> <label for="name">Username</label> ...

Troubleshooting issue with image dimensions in Angular within CKEditor content

One issue I am facing is with CKEditor, where images inserted into Rich Text Fields have their height and width attributes set in a CSS style tag. For example: <img alt="" src="https://something.cloudfront.net/something.jpg" style="height:402px; ...

jQuery plugin stops functioning properly following the use of the jQuery display block method

In my project, I am exploring the use of divs as tabs with jQuery. Within these divs, I also want to incorporate another jQuery plugin. Currently, I have manually created these div tabs using jQuery and set the default style for second and subsequent divs ...

What is the purpose of type casting in Typescript?

As a TS newcomer, I have a question that surprisingly lacks a clear explanation. What is the main difference between specifying the type to TypeScript in these two ways: const ul = document.querySelector('#nav') as HTMLUListElement; and this way ...

The method selObj.fireEvent is undefined and cannot be executed

There is a function in a JavaScript file that retrieves a menu tree when users click on the parent item: function menusel(unid) { //if its in the array, deactivate it and take it out var index = inarray(unid,selectedarray); //first arrange ...

Switching the class does not initiate the transition

I'm having trouble getting a transition to work when toggling a class. The class is being applied and the style changes accordingly, but the transition isn't triggering. I've checked that the transition applies to all properties, so I don&ap ...

'Error: Script ngcc is missing in NPM' - Issue encountered

Out of nowhere, my Visual Studio Code project suddenly began showing two strange errors like this: click to view image All the tags from Angular Material are now being marked as errors, failing to get recognized as valid tags. Attempting to use npm run n ...

What is the method for defining the current date variable within a .json object?

When using a post .json method to send an object, I encounter the following situation: { "targetSigningDate": "2021-09-22T21:00:00.000Z" } The "targetSigningDate" always needs to be 'sysdate'. Rather than manually c ...

The user in req.session is not defined within a Next.js iron-session

I'm currently working on a dashboard for our team's bot that utilizes next.js and iron-session. However, I've run into an issue where req.session.user is showing up as undefined when I try to save the session. How can I go about fixing this ...

Error encountered during the build process in Angular microfrontends/multirepos using Webpack external module

I have developed an Angular project to integrate a microfrontend with another running Angular project. I have successfully imported the module into my application using webpack.config.js. Everything works fine on my local environment, but I encounter issue ...