【问题标题】:I would like to use the selection from the material table but it's not working - Material Table Selection我想使用材料表中的选择,但它不起作用 - 材料表选择
【发布时间】:2020-03-31 07:00:42
【问题描述】:

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

这是我的 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 中,我导入了我需要的所有东西。 可能是什么问题?这部分我写得不好?

【问题讨论】:

    标签: typescript angular-material-table


    【解决方案1】:

    您需要输入: displayedColumns: string[] = ['select', 'id', 'name', 'code']; 并从您的 HTML 文件中调用它:

    (它将呈现您的列)。

    关键是不要忘记在显示的列中添加“select”字段,因为它还显示带有复选框的列,就像界面中的其他字段一样。 p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 2020-07-05
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2020-08-30
      相关资源
      最近更新 更多