Как мне установить флажки слева от таблицы, созданной с помощью Angular 6? - PullRequest
0 голосов
/ 18 февраля 2019

Ниже находится мой файл 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() { }
}

Ранее я мог установить флажки, следуя примеру в Таблица угловых материалов , но когда я заполнял таблицу с помощью внешнего API, функции isAllSelected() и masterToggle() начинают выдавать ошибку.Что я должен отредактировать, чтобы функции снова заработали?

1 Ответ

0 голосов
/ 18 февраля 2019

Что ж, класс 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';

Здесь - это стек, который показывает рабочий пример с MatTableDataSource.pipe(delay(1500)) просто для имитации асинхронного запроса данных.

...