Kelvin Low
Kelvin Low

Reputation: 746

How do I implement checkboxes at the left of the table created with Angular 6?

Below is my TS file.

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() { }
}

I was previously able to implement checkboxes by following the example in Angular Material Table, but when I populate the table using external API, the functions isAllSelected() and masterToggle() start giving error. What should I edit to make the functions work again?

Upvotes: 0

Views: 137

Answers (1)

Fabian K&#252;ng
Fabian K&#252;ng

Reputation: 6183

Well for one the DataSource class does not have a data property, therefore your solution will not work. Instead of extending the DataSource, I would extend the MatTableDataSource.

If you change your data source to the following:

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

Don't forget to import the MatTableDataSource:

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

Here is a stackblitz that shows a working example with the MatTableDataSource. The pipe(delay(1500)) is just there to simulate an async data request.

Upvotes: 2

Related Questions