0
votes

I have added checkboxs to my material table. Everything is working fine apart from when I select all the child checkboxes manually the header checkbox is not checked.

HTML code:

<ng-container matColumnDef="select">
            <mat-header-cell *matHeaderCellDef>
              <label class="Ai-checkbox">
                        <input class="inputCheckBox" type="checkbox" name="checkBox" value="all" (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()"
                        [indeterminate]="selection.hasValue() && !isAllSelected()">
                      </label>
            </mat-header-cell>

            <mat-cell *matCellDef="let row">
              <label class="Ai-checkbox">
                <input class="inputCheckBox" type="checkbox" name="checkBox" value="all" (click)="$event.stopPropagation()"
                  (change)="$event ? selection.toggle(row) : null" [checked]="selection.isSelected(row)">
              </label>
            </mat-cell>
          </ng-container>

TS File:

 /** Whether the number of selected elements matches the total number of rows. */
 isAllSelected(){
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }

What am I doing wrong ? enter image description here

1

1 Answers

0
votes

you can try my code:

in .html :

<mat-card>
  <mat-card-content>
    <h2 class="example-h2">Checkbox configuration</h2>

    <section class="example-section">
      <mat-checkbox (click)="CheckAllOptions()"class="example-margin" [(ngModel)]="checked">Checked</mat-checkbox>
    </section>

    <div *ngFor="let checkbox of checkboxes">
    <input type="checkbox" [(ngModel)]="checkbox.checked" [value]="checkbox.value"><span>{{checkbox.name}}</span>
</div>

  </mat-card-content>
</mat-card>

at .ts into export class:

checkboxes: any[] = [
    { name: 'cb1', value: 'cb1', checked: false },
    { name: 'cb2', value: 'cb2', checked: true },
    { name: 'cb3', value: 'cb3', checked: false },
    { name: 'cb4', value: 'cb4', checked: false },
    { name: 'cb5', value: 'cb5', checked: false },
  ]

  CheckAllOptions() {
    if (this.checkboxes.every(val => val.checked == true))
      this.checkboxes.forEach(val => { val.checked = false });
    else
      this.checkboxes.forEach(val => { val.checked = true });
  }