以下是我的TS文件。



import { Component, OnInit } from '@angular/core';
import { SelectionModel, DataSource } from '@angular/cdk/collections';
import { OrdersService } from '../orders.service';
import { Observable } from 'rxjs/Observable';

export interface DataTableItem {
  name: string;
  email: string;
  phone: string;
  company: {
    name: string;
  };
}

@Component({
  // tslint:disable-next-line:component-selector
  selector: 'data-table',
  templateUrl: './data-table.component.html',
  styleUrls: ['./data-table.component.css']
})

export class DataTableComponent implements OnInit {

  dataSource = new UserDataSource(this.orderService);
  selection = new SelectionModel<any>(true, []);

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['name', 'email', 'phone', 'company'];

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

  constructor(private orderService: OrdersService) { }

  ngOnInit() {
    console.log(JSON.stringify(this.dataSource));
  }
}

export class UserDataSource extends DataSource<any> {
  constructor(private orderService: OrdersService) {
    super();
  }

  connect(): Observable<DataTableItem[]> {
    return this.orderService.GetTestData();
  }

  disconnect() { }
}





我以前可以通过遵循Angular Material Table中的示例来实现复选框,但是当我使用外部API填充表时,函数isAllSelected()masterToggle()开始出错。我应该编辑什么以使功能再次起作用?

最佳答案

好吧,DataSource类没有一个data属性,因此您的解决方案将无法工作。除了扩展DataSource,我将扩展MatTableDataSource

如果您将数据源更改为以下内容:

export class UserDataSource extends MatTableDataSource<any> {
  constructor(private orderService: OrdersService) {
    super();
    this.orderService.GetTestData().subscribe(d => {
      this.data = d;
    });
  }
}


不要忘记导入MatTableDataSource

import { MatTableDataSource } from '@angular/material';



  Here
  是一个堆栈闪电战,展示了
  MatTableDataSourcepipe(delay(1500))就在那里
  模拟异步数据请求。

09-17 08:23