Deactivate dynamically created checkboxes when 2 checkboxes are selected in Angular

I am using FormArray and Reactive Forms Module to dynamically generate checkboxes.

My requirement is to disable the remaining checkboxes once the user selects any 2 checkboxes. If the user deselects one, they should be able to select from the others again. When 2 selections are made, all other checkboxes should be disabled.

Here is the HTML code:


    <form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
    <label>
      <b>Time Out Period :</b>
    </label>
    <div class="input-group">
      <input type="text" class="form-control" maxlength="2" formControlName="tbl_config_TimeoutPeriod">
    </div>
    <div *ngIf="tbl_config_TimeoutPeriod.invalid && tbl_config_TimeoutPeriod.touched">
      <span style="color:red;margin-top:3px">Time Out Period field is mandatory..!</span>
    </div>
    <br>
    <div formArrayName="users">
      <div *ngFor="let user of users.controls; index as idx">
        <input [formControlName]="idx" type="checkbox"   >
        <button (click)="deleteUserField(idx)">Delete</button>
      </div>
    </div>
    <br>
    <button type="submit" [disabled]="!userForm.valid" class="btn btn-primary">Save Changes</button>
    <button type="button" (click)="addUserField()">Add More User</button>
  </form>

Following is the TypeScript code:


  userForm = new FormGroup({
        tbl_config_TimeoutPeriod: new FormControl('', Validators.required),
        users: new FormArray([
          new FormControl('', Validators.required)
        ])
      });

 get users(): FormArray { return this.userForm.get('users') as FormArray; }
  get tbl_config_TimeoutPeriod() { return this.userForm.get('tbl_config_TimeoutPeriod'); }

  onFormSubmit() {
    console.log(this.userForm.value); // Provides complete form data
  }

  addUserField() {
      this.users.push(new FormControl(''));
  }

  deleteUserField(index: number) {
    this.users.removeAt(index);
  }

Answer №1

If you want to modify your input, try the following:

    <input type="checkbox" 
        [disabled]="amountChecked==2&&!input.checked
            ?'disabled'
            :''" 
        (change)="handleCheck($event.target)" 
        #input>

To go along with this change, add the following to your component.ts file:

amountChecked=0
handleCheck(ev){
  if(ev.target.checked==true){
    this.amountChecked++
  }else{
    this.amountChecked--
  }
}

Furthermore, make adjustments to the deleteUserField() method:

deleteUserField(index: number,el:HTMLInputElement) {
  el.checked=false
  this.handleCheck(el)
  this.users.removeAt(index);
}

Take a look at the proof of concept here

  • The amountChecked property will update whenever a checkbox is changed, keeping track of how many checkboxes are checked.
  • The [disabled] attribute is tied to a specific value (in this case, 2), so when that number of checkboxes is selected, the non-checked boxes become disabled.
  • The template reference variable, #input, is designated for each iteration in the ngFor-loop to refer specifically to the current input element and prevent disabling the already checked checkboxes.

Edit

In response to requests, I have revised the link in the example, consolidated all code from the original question with my solution, and made necessary updates both above and in the demonstration to allow for deleting inputs and managing state accurately.

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

Error: The variable "redirectTo" has not been declared. This error can be found in the

I recently embarked on my journey to learn Angular2. I diligently followed the documentation and watched some helpful YouTube tutorials to guide me through the process. However, I've hit a roadblock while trying to configure the routes in my project. ...

Delay experienced when transitioning from the main page to a form within an Ionic Angular application

Home Page|ionic form|ionic issueI recently developed an ionic angular application. In this app, I have designed a form and added a button on the home page that redirects to the form. However, I am facing an issue where there is a noticeable lag when transi ...

What is the best way to align text in the middle of a path

I have an array of paths from the backend server, which I will use to create a custom floor plan. Each path needs to be associated with a name that is both visible and editable, located precisely at the center of each path. <svg viewBox="0 0 2000 1 ...

Exploring async componentDidMount testing using Jest and Enzyme with React

angular:12.4.0 mocha: "8.1.2" puppeteer: 6.6.0 babel: 7.3.1 sample code: class Example extends Angular.Component<undefined,undefined>{ test:number; async componentWillMount() { this.test = 50; let jest = await import('jest&apos ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

Angular Issue: Showing custom validator error messages

I have implemented custom validators in an Angular form that I created. The validators are functioning correctly, but now I want to display an error message on the form indicating if there is a validation issue with the field. After referring to this webs ...

Having trouble retrieving the client access token from Dialog Flow, I must find a way to integrate it into my Angular application

When I first started as a beginner, I decided to dive into developing a sample chatbot using Angular and DialogFlow. However, I quickly ran into an issue where I couldn't access the client access token. Despite my efforts, such as trying the "gcloud a ...

Ways to retrieve data object within an HTMLElement without relying on jQuery

Within my web application, I have successfully linked a jQuery keyboard to a textbox. Now, I am seeking a way to explicitly call the keyboard.close() function on the keyboard as I am removing all eventListeners from the text field early on. To achieve thi ...

What is the best way to implement the Vue router in a separate file?

The vue-router is currently working well, but we are interested in pushing a route from another file. Here is an example of the code: // src/router/index.ts import { route } from 'quasar/wrappers' import VueRouter from 'vue-router' impo ...

Incorporating Swagger-UI into an Angular 10 project

Looking to integrate Swagger UI into your Angular application? After researching extensively, I found that the recommended approach is now to use the swagger-ui package instead of swagger-ui-dist for single-page applications. For those using React, there ...

Creating a Typescript interface that includes double arrow functions is a great way to define the

How can a typescript interface be written using the double arrow function es6 syntax? JavaScript Example: const myFunction => (param1) => (param2) => { ...code } TypeScript Example: const myFunc = (param1: number) => (param2: number) => ...

The real file that was brought in after indicating a module in the node_modules directory that was coded in Typescript

After creating a typescript module named moduleA, I am ready to publish this package and make it accessible from another typescript project. Currently, for testing purposes, I have installed 'moduleA' using 'npm install ../moduleA'. Th ...

Implementing ExpressJS functionality within a TypeScript class

Searching through numerous examples of ExpressJS and TypeScript, I noticed they all follow a similar pattern: import * as express from "express"; let app = express(); app.use("/", express.static("/")); However, my preference is to employ the class appro ...

Guide on packaging an Angular 2 Typescript application with Gulp and SystemJS

In my Angular 2 project, I am using Typescript with SystemJS for module loading and Gulp as a task runner. Currently, the project is running on Angular RC2 but the same issue persists with RC1. I followed the steps provided in brando's answer here. U ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

Refresh angular view after closing the modal box

Is it possible to use Angular 5 to update an attribute in the parent component when a child component (modal dialog) is closed? Are all three of these methods effective, and which one would provide the quickest results with the least amount of overhead? M ...

Form a combination of distinct elements from an array of unique types in typescript

I am wondering if it is possible to define an array of unique types based on a union of those types. Let's say I have the following type Value: type Value = string | number Then, I attempted to create a type called Values like this: type Values = ...

Is it possible to release a typescript package without including the ts files in the

I have a Typescript project that needs to be published. All generated JS files are stored in a directory named build, and declaration files in another directory called declaration. I do not want the .ts files to be included in the published version. Can an ...

Designing a TypeScript declaration file for a Vue library (Vue DateTime)

Currently, I am utilizing Vue.js along with Typescript for my project. My intention is to incorporate the vue-datetime package. However, since this package lacks a Typescript definition file, I have taken the initiative to create a basic version myself. T ...

TYPESCRIPT: The argument labeled as 'typeof X' cannot be assigned to the parameter labeled as 'Y' that extends

As I venture into coding with TypeScript, I am encountering some compilation issues. It appears that I am facing a hierarchy problem with several classes. The first class (A) defines a set of properties/functions. The second class (B) inherits from class ...