Select all items in a checkbox Angular

Viewed 784

I have a list which has multiple checkboxes. I have made a function for single selection and multiple section and the user can get the data either for single selection and multiple selection. Now the problem where I was stuck was when I remove selection of one check box in a list then select all checkbox should be deselected but I'm not able to do that.

Below is my code HTML

  <div item-start class="checkbox-wrapper">
    <input type="checkbox" value="Select All" (change)="selectAllLineItem($event)">
  </div>

    <ion-card *ngFor="let putAwayPurchaseOrderListDetails of putAwayPurchaseOrderListDetailsData | filter:searchText; let i = index">
       <div class="checkbox-wrapper">
         <input class="form-check-input[(ngModel)]="putAwayPurchaseOrderListDetailsData[i].checked"  type="checkbox" >
       </div>
       <div>
         {{putAwayPurchaseOrderListDetails.PO_NUMBER}}
       </div>
    </ion-card>

TS

  selectedLineItem() {
    const selectedLineItem = this.putAwayPurchaseOrderListDetailsData.filter((putAwayPurchaseOrderListDetails) => putAwayPurchaseOrderListDetails.checked);
    this.navCtrl.push(PutAwayPurchaseOrderItemDetailsPage,{selectedLineItem})   
  }


  selectAllLineItem(event) {
    console.log(event)
    const checked = event.target.checked;
    this.putAwayPurchaseOrderListDetailsData.forEach(item => item.checked = checked);
  }
1 Answers

A quick, possible solution.

First, you split the ngModel double binding and create an handler:

...
<input type="checkbox" value="Select All" [(ngModel)]="selectAllItems" (change)="selectAllLineItem($event)">
...
<input class="form-check input 
    [ngModel]="putAwayPurchaseOrderListDetailsData[i].checked"
    (ngModelChange)="onItemChange(i, $event)"
    type="checkbox" >

In the component ts:

// new property:
selectAllItems: boolean = false;
...
onItemChange(itemIdx: number, isChecked: boolean) {
  this.putAwayPurchaseOrderListDetailsData[itemIdx].checked = isChecked;
  // doesn't if selectAllItems is already false.
  if (!isChecked) this.selectAllItems = false;
}

It should be enough.

Related