【问题标题】:Header checkbox is not checked when all child checkboxes are selected in angular material在角度材料中选择所有子复选框时,不选中标题复选框
【发布时间】:2020-07-13 14:46:21
【问题描述】:

我已在我的材料表中添加了复选框。除了我手动选择所有子复选框之外,一切都工作正常,标题复选框未选中。

HTML 代码:

<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 文件:

 /** 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));
  }

我做错了什么?

【问题讨论】:

    标签: angular checkbox angular-material


    【解决方案1】:

    你可以试试我的代码:

    在 .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 进入导出类:

    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 });
      }
    

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 2019-06-02
      • 2014-06-20
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      • 2017-11-26
      • 2013-04-26
      相关资源
      最近更新 更多