Home > Enterprise >  leave a mandatory checkbox using a list of items populated with ngFor
leave a mandatory checkbox using a list of items populated with ngFor

Time:03-23

I have an array with items, and with that I populate an ngFor that it shows me my list of items with my checkboxes, I need to make a validation that leaves at least one of these items mandatory.

An example is = if one checkbox is CHECKED and the other is UNCHECKED, I can't uncheck the checkbox that is CHECKED, I need to leave disabled only the one that was checked, I can only uncheck it, if I CHECK my checkbox that was unchecked, so it gets enabled and so on.

I tried this

<div *ngFor="let item of dataList"\>
<input type="checkbox" [checked\]="item.checked" (change)="itemSelected($event, item)" [disabled]="notSelectCheck">

itemSelected(value, level ) {
level.checked = value.target.checked

const valuesChecked = this.dataList.filter((dt) =\> dt.checked).length;

valuesChecked \< 2 ? (this.notSelectCheck = true) : (this.notSelectCheck = false)

}

CodePudding user response:

This will keep the last checkbox always checked, and allow you to check as many ones as you want. You just need to count the number of checked elements and use preventDefault() if the total ones checked==1:

<div *ngFor="let element of elements; let i = index">
  <input
    name="elem{{ i }}"
    id="elem{{ i }}"
    [(ngModel)]="element.checked"
    type="checkbox"
    [checked]="element.checked"
    (click)="checkElement($event, i)"
  />
  <label for="elem{{ i }}">{{ element.text }}</label>
</div>

.ts

elements: any = [
    {
      checked: true,
      text: 'Element 1',
    },
    {
      checked: true,
      text: 'Element 2',
    },
    {
      checked: true,
      text: 'Element 3',
    },
    {
      checked: false,
      text: 'Element 4',
    },
  ];

  checkElement(e: any, index: number) {
    //checks if the user is checking or unchecking a checkbox
    if (!e.target.checked) {
      //if the user unchecked a checkbox, then I count the number of checked checkboxes
      let totalChecked = 0;
      for (let checked of this.elements) {
        if (checked.checked) {
          totalChecked = totalChecked   1;
        }
      }
      //if the number of checked checkboxes is 1, then I cancel the uncheck action with e.preventDefault(), and reassign true to the unchecked value.
      if (totalChecked == 1) {
        e.preventDefault();
        this.elements[index].checked = true;
      }
    }
  }
  • Related