如何启用在Mat表中选中单个复选框的按钮?

时间:2018-11-14 14:50:56

标签: angular angular6 typescript2.0 angular-material-6 mat-table

如果选中“ td”标签中的单个复选框,则需要启用“提交”按钮,如果选中“ th”标签中的主复选框,则其工作正常。我正在使用角形材料。预先感谢。

找到Stackblitz链接:https://angular-material2-5cgxqf.stackblitz.io/

app.component.html

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <!-- Checkbox Column -->
    <ng-container matColumnDef="select">
        <th mat-header-cell *matHeaderCellDef>
            <mat-checkbox (change)="$event ? masterToggle() : null"
                    [checked]="selection.hasValue() && isAllSelected()"
                    [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>
        </th>
        <td mat-cell *matCellDef="let row">
            <mat-checkbox (click)="$event.stopPropagation()"
                    (change)="$event ? selection.toggle(row) : null"
                    [checked]="selection.isSelected(row)"></mat-checkbox>
        </td>
    </ng-container>
</table>
/**Button*/

<button [disabled]="isButtonEnable">Submit</button>

app.component.ts

import {SelectionModel} from '@angular/cdk/collections';
import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material';

isButtonEnable:boolean =true;
/** 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() {
      if(this.isAllSelected()){
              this.selection.clear();
              this.isButtonEnable = true;
          }else{
              this.dataSource.data.forEach(row => this.selection.select(row));
              this.isButtonEnable = false;
      }
  }

2 个答案:

答案 0 :(得分:1)

您应该在任何复选框中检查是否有任何更改。如果选中任何复选框,则应启用提交按钮。添加以下代码段。

  constructor(){
    this.selection.changed.subscribe(item=>{
      this.isButtonEnable = this.selection.selected.length == 0;
    })
  }

这是工作示例-https://stackblitz.com/edit/angular-material2-p8r4pe

答案 1 :(得分:0)

app.component.html

<mat-checkbox (click)="SingleSelection(); $event.stopPropagation()"
                        (change)="$event ? selection.toggle(row) : null"
                        [checked]="selection.isSelected(row)">
          </mat-checkbox>

app.component.ts

SingleSelection(){
    const numSelected = this.selection.selected.length;
      numSelected <= 0 ? this.isButtonEnable = false : this.isButtonEnable = true;
  }

这也可以正常工作,请找到链接:https://stackblitz.com/edit/angular-material2-p8r4pe?file=app%2Fapp.component.ts