I
I
Ivan Stroykin2017-07-18 14:03:04
Angular
Ivan Stroykin, 2017-07-18 14:03:04

How to properly work with datatable from Angular Material?

Good day,
Who has already tried datatable from angular material? Although I sat behind it for a bit, I found a good plus, which is that you can simply describe all the columns, and then simply call only those that you need and in any order. The downside is that I can't just get it to work. I always get the error:
this.dataSource.connect is not a function
The bottom line is that the data comes from the backend in json format (in the example, the data is, of course, "hard-coded")
Example on Plunker

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2017-07-18
@StivinKing

The table is not quite simple, we must pass the dataSource as an object of the DataSource type from @angular/cdk

/**
   * Provides a stream containing the latest data array to render. Influenced by the table's
   * stream of view window (what rows are currently on screen).
   */
  @Input()
  get dataSource(): DataSource<T> { return this._dataSource; }

Here's your next step
import { DataSource } from '@angular/cdk'
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/of'

export class MyDataSource extends DataSource<any> {
  connect(): Observable<any[]> {
    return Observable.of([
      {id: 1, title: 'Test 1'},
      {id: 2, title: 'Test 2'},
      {id: 3, title: 'Test 3'},
    ]);
  }

  disconnect() {}
}


public dataSource: DataSource = new MyDataSource();

https://plnkr.co/edit/I5gnn3XzosabC8lQCrEo?p=preview
This kind of encourages us to keep learning rxjs and learn all its power. Next, go to the examples on the site https://material.angular.io/components/table/examples, there is a more advanced version of the connect method, where the merge operator is used

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question