mercredi 20 janvier 2021

Limit number of selected checkbox, but allow to unselect a checkbox Angular 10

I checked other threads, but no one with Typescript and not Jquery.

I would like to be able to select 2 checkbox, but no more. I would to keep the ability to unselect a previous one that has been selected. I'm using Typescript with Angular 10. No Jquery, and i don't want it.

Actually : I can select 2 checkbox, and then they are ALL disabled. So i can't unselect a previous one..

Html :

<nb-checkbox [disabled]="disableCheckbox()" (change)="changeSelection($event, item.id)" [checked]="false">A checkbox</nb-checkbox>

Typescript :

checkboxList = [];
public maxElementCheckbox = 2;

changeSelection($event, id){

    if ($event.target.checked) {
      this.checkboxList.push(id);
    }  else {
      this.checkboxList.splice(this.checkboxList.indexOf(id), 1);
    }
    console.log(this.checkboxList);
  }

  public disableCheckbox(): boolean {
    return this.checkboxList.length >= this.maxElementCheckbox;
  }

Thanks for help




Aucun commentaire:

Enregistrer un commentaire