Ensure that a required checkbox is included within a list of items generated dynamically through ngFor

I am working with an array of items in Angular, using ngFor to display a list of checkboxes. I need to implement validation that ensures at least one checkbox remains mandatory.

For example, if one checkbox is checked and another is unchecked, I want to prevent unchecking the checked box. Only when the unchecked box is selected, should the previously checked box be enabled.

Here is what I have attempted:

<div *ngFor="let item of dataList"\>
<input type="checkbox" [checked\]="item.checked" (change)="itemSelected($event, item)" [disabled]="notSelectCheck">

itemSelected(value, level ) {
level.checked = value.target.checked

const valuesChecked = this.dataList.filter((dt) =\> dt.checked).length;

valuesChecked \< 2 ? (this.notSelectCheck = true) : (this.notSelectCheck = false)

}

Answer №1

By implementing this code snippet, you can ensure that the last checkbox remains checked while allowing users to check as many others as they want. The key is to keep track of the number of checkboxes that are checked and utilize preventDefault() when only one checkbox is checked:

<div *ngFor="let element of elements; let i = index">
  <input
    name="elem{{ i }}"
    id="elem{{ i }}"
    [(ngModel)]="element.checked"
    type="checkbox"
    [checked]="element.checked"
    (click)="checkElement($event, i)"
  />
  <label for="elem{{ i }}">{{ element.text }}</label>
</div>

.ts

elements: any = [
    {
      checked: true,
      text: 'Element 1',
    },
    {
      checked: true,
      text: 'Element 2',
    },
    {
      checked: true,
      text: 'Element 3',
    },
    {
      checked: false,
      text: 'Element 4',
    },
  ];

  checkElement(e: any, index: number) {
    // Determine if the user is checking or unchecking a checkbox
    if (!e.target.checked) {
      // If a checkbox is unchecked, count the number of checked boxes
      let totalChecked = 0;
      for (let checked of this.elements) {
        if (checked.checked) {
          totalChecked++;
        }
      }
      // Prevent unchecking if only one checkbox is checked, revert it to checked state
      if (totalChecked === 1) {
        e.preventDefault();
        this.elements[index].checked = true;
      }
    }
  }

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

Converting Angular App's local storage from synchronous to asynchronous with Indexed-db

I am utilizing local storage to retrieve data and if the data is not available in local storage, then I make a server API call, add the data to storage for future use, and return the data. This ensures that next time, the data will be retrieved from storag ...

Error: The TranslateService provider is not found and needs to be added to the

When attempting to make translation dynamic in angular2 using the ng2-translation package, I encountered an error message: Unhandled Promise rejection: No provider for TranslateService! zone.js:388Unhandled Promise rejection: No provider for TranslateSe ...

Exploring the use of global variables in Firebase authentication with TypeScript

I declared a variable called user outside of the specified scope. However, I am encountering difficulties in accessing this.user within the function firebase.auth().signInWithPopup(provider).then((result) => {. It keeps displaying as undefined. i ...

Enforce numerical input in input field by implementing a custom validator in Angular 2

After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer. The desired functionality for the custom validator is to restrict input to ...

Setting base URLs for production and development in Angular 6: A step-by-step guide

As a beginner in Angular, I am looking for a way to set different base URLs for production and development environments. I aim to dynamically configure the base URL to avoid hard-coding it in the index.html file every time I switch between these two enviro ...

What could be causing Angular's Renderer2 to generate inaccurate outcomes?

Having an array of queries with varying positions of underscores: Newtons __________ Law dictates __________ is the result of an object's mass and speed. My goal is to show each question to users, replacing the blanks with in ...

Looking to update the URL from another component?

My current project is using Angular 6 and I am working on creating a list of buttons on the left panel such as "Ice cream", "Pop corns", and more. The goal is for users to click on these buttons which will then change the URL of the add button located in t ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Cease the RxJS HTTP Polling upon receiving a successful HTTP response

In my code, I have implemented a polling mechanism to mimic HTTP Requests. The goal is to stop sending requests if the server responds with data.length > 0. timeout:Observable<number> = timer(10000); startPollingStackblitz(arnId: string) { ...

Guide on importing SVG files dynamically from a web service and displaying them directly inline

With an extensive collection of SVG files on hand, my goal is to render them inline. Utilizing create-react-app, which comes equipped with @svgr/webpack, I am able to seamlessly add SVG inline as shown below: import { ReactComponent as SvgImage } from &apo ...

Tips for Updating a specific value in Angular 2

I am currently utilizing Angular 2+ alongside Material (https://material.angular.io). The stepper component is being used to create a straightforward form. Overall, it functions smoothly, except for one particular scenario. I aim to dynamically alter the v ...

Using a loop variable within a callback function in JavaScript/TypeScript: Tips and tricks

I have a method in my TypeScript file that looks like this: getInitialBatches() { var i = 0; for (var dto of this.transferDTO.stockMovesDTOs) { i++; this.queryResourceService .getBatchIdUsingGET(this.batchParams) ...

What is the best way to implement show more and show less functionality for content in Angular 6?

We currently have 6 content divs with character limits applied to each one. Our setup includes Bootstrap 4 and Angular 6. In the 6 divs, some toggle div content is open while others are closed. How can we achieve this dynamic toggling effect? ...

Exploring the integration of angular with html5 history.pushstate for navigation

Currently, I am enhancing my web application by implementing a new feature. This feature involves writing a script and loading it via a tag manager. The purpose of this script is to target specific UI components, remove them from the DOM, and inject new DO ...

What is the process for integrating a third party API certificate into my Heroku application?

When my backend service calls a third-party API (Kamer van koophandel) to retrieve data, it requires a certificate to be set. It functions correctly locally, but upon pushing to Heroku, the following error occurs: Warning: Ignoring extra certs from `Privat ...

Angular is utilized to create a dynamic multiple slide carousel that features repeating items

There is a problem with the carousel I am working on where the items are duplicated after resizing the screen. The code I am using is based on Eliseo's solution from this Stack Overflow thread. In his carousel, the arrow functions show/hide depending ...

Tips for Maintaining User Data Across Pages in React using React-Router-Dom and Context

I've been tackling the login functionality of a client-side application. Utilizing React alongside TypeScript, I've incorporated react-router-dom and Context to manage the user's data when they log in. However, upon refreshing the page, the ...

What is the most effective method for delivering a Promise after an asynchronous request?

Currently, I am working on creating an asynchronous function in TypeScript that utilizes axios to make an HTTP request and then returns a Promise for the requested data. export async function loadSingleArweaveAbstraction(absId : string) : Promise<Abstra ...

Updating Angular from version 9 to 11 causes issues with router.navigate not being able to properly load a new component

After updating my Angular project from version 9 to 11 (with an upgrade to version 10 in between), I encountered a strange routing issue. In version 9, the method below worked perfectly fine. However, in version 11, although the URL changed to 'upload ...

Binding the "name" attribute of <input> elements using Angular2's *ngFor directive

Currently, I am delving into Angular2 and Angular Material. My approach involved utilizing *ngFor to have Angular dynamically generate the <input> elements for me. However, upon inspecting the resulting webpage, I noticed that the generated element w ...