1

Trying to set limitation for checkbox but not working. If i select more then 2 check box i want to not allow to select. I have tried but not working properly. If anyone knows please help to find the solutions.

mauto.component.ts:

toggleSelection = (data: ItemData): void => {
     data.selected = !data.selected; 
       if (data.selected === true) { 
           if(this.selectData.length <= 1) {
               this.selectData.push(data);
       } else {
         data.selected = false;
         alert("You can select only 2");
       } 
  }

Demo : https://stackblitz.com/edit/angular-ivy-enwmdh?file=src%2Fapp%2Fshared%2Fmauto%2Fmauto.component.ts

EMahan K
  • 417
  • 1
  • 19

1 Answers1

2

Create a flag that will tell your template when to start disabling checkbox, and update it inside your toggleSelection() function.

toggleSelection = (data: ItemData): void => {
   ...
   ...

   this.disableCheckbox = this.selectData.filter(item => item.selected === true).length >= 2;

   ...
   ...
}

Then use it in the template to disable unselected checkboxes, when already 2 are selected. You should keep the checked boxes enabled, in case if user wants to deselect any of them.

<mat-checkbox
  [checked]="data.selected"
  (change)="toggleSelection(data)"
  (click)="$event.stopPropagation()"
  [disabled]="disableCheckbox && !data.selected"
>

Demo

Nehal
  • 13,130
  • 4
  • 43
  • 59
  • So, No need to add like this rite? if(this.selectData.length <= 1) { – EMahan K Aug 04 '22 at 13:04
  • Yes, you can removed it, I tested it in the demo, works fine. Please accept and upvote if it solves your question, thanks. – Nehal Aug 04 '22 at 13:13