首页 > 解决方案 > 我想使用材料表中的选择,但它不起作用 - 材料表选择

问题描述

我的问题是我想使用材料表中的选择,但由于某种原因它在表面中有它的位置,但复选框没有出现。

这是我的 HTML 代码:

  <table mat-table [dataSource]="dataSource" mat-elevation-z8>

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

  <!-- ... -->

  </table>

还有我的 TS 文件:

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

export abstract class MyClass implements OnInit {
    devizas: DevizaInterface[] = [
    {
      id: '1',
      name: 'dollar',
      code: 'USD' ,
    }
    //...
  ];
  dataSource = new MatTableDataSource<DevizaInterface>(devizas);
  selection = new SelectionModel<DevizaInterface> (true, []);

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }

  checkboxLabel(row?: PeriodicElement): string {
    if (!row) {
      return `${this.isAllSelected() ? 'select' : 'deselect'} all`;
    }
    return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.id + 1}`;
  }

}



我按照文档中的说明做了所有事情,其他功能(排序、过滤)没有问题。在 app.module.ts 中,我导入了我需要的所有东西。可能是什么问题?哪一部分我写得不好?

标签: typescriptangular-material-table

解决方案


您需要输入: displayedColumns: string[] = ['select', 'id', 'name', 'code']; 并从您的 HTML 文件中调用它: <tr mat-h​​eader-row *matHeaderRowDef="displayedColumns"> (它将呈现您的列)。

关键是不要忘记在显示的列中添加“选择”字段,因为它还显示带有复选框的列,因为它是界面的一部分的其他字段。


推荐阅读