Mercy
Mercy

Reputation: 67

I want user to select only one checkbox instead of multiple? How can I approach in angular?

I have multiple checkboxes but I want user to select one checkbox but not multiple, if he check one checkbox and it returns checked value, else nothing should show up.can anyone help?

<div class="form-check" *ngFor="let product of DisplayProductList">
    <label class="form-check-label text-break">
        <input class="form-check-input" type="checkbox" [value]="true" [(ngModel)]="product.isChecked"
            (change)="changeSelection($event)" />
        {{ product.template_name }}
        <span class="form-check-sign">
            <span class="check"></span>
        </span>
    </label>
</div>
changeSelection(event: any) {
  this.checkedIDs = [];
  if (event.target.checked) {
    this.selectedItemsList = this.DisplayProductList.filter(
      (product, index) => {
        if (product.isChecked == true) {
          let splitstring = product.template_parameter;
          let sepratedArray = splitstring.split(',');
          this.variable1 = sepratedArray[0];
          this.variable2 = sepratedArray[1];
          this.checkedIDs.push(product.id);

          this.sendclusteridApi(this.productid);
          return product.isChecked;
        }
      }
    );
  }
}

Upvotes: 2

Views: 13009

Answers (1)

Amer
Amer

Reputation: 6706

As mentioned in the comments, this is what radio buttons do, but if you need to implement the same functionality using checkboxes, you can achieve that like the following:

  • Define a selectedIndex variable, and assign to it the index of the last checked checkbox.
  • Bind the ngModel of the checkboxes to [ngModel]="selectedIndex === index" where the index is the index of the checkbox within the *ngFor loop.
<div class="form-check" *ngFor="let product of DisplayProductList; let index = index">
  <label class="form-check-label text-break">
    <input class="form-check-input" type="checkbox" [ngModel]="selectedIndex === index"
        (change)="changeSelection($event, index)" />
    {{ product.template_name }}
    <span class="form-check-sign">
        <span class="check"></span>
    </span>
</label>
</div>
selectedIndex: number;

changeSelection(event, index) {
  this.selectedIndex = event.target.checked ? index : undefined;

  // do your logic here...
}

Upvotes: 4

Related Questions