Search code examples
typescriptangular-material2angular-material-7angular14

How to set limitation for mat checkbox in angular 14


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


Solution

  • 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