如何在使用Angular 6创建的表的左侧实现复选框?

问题描述 投票:0回答:1

下面是我的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()开始给出错误。我应该编辑什么才能使功能再次起作用?

javascript angular typescript angular-material frontend
1个回答
2
投票

好吧,一个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是一个stackblitz,显示了MatTableDataSource的工作示例。 pipe(delay(1500))就是为了模拟异步数据请求。

© www.soinside.com 2019 - 2024. All rights reserved.