dataSource.connect is not a function when using Material datatable

Hamza Haddad picture Hamza Haddad · Mar 4, 2018 · Viewed 7.2k times · Source

I would use material datatable with dataSource as array.

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { AjouttextService } from '../ajouttext.service';
import { DataSource } from "@angular/cdk/collections";
import { Observable } from "rxjs/Observable";
import { nomchamp } from '../model';

@Component({
  selector: 'app-datatable',
  templateUrl: './datatable.component.html',
  styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {

  constructor(private dataService: AjouttextService) { }
  data: nomchamp[] = [{ id: "33", text: "HAHA" }, { id: "55", text: "bzlblz" }];

  displayedColumns = ['text'];
  dataSource = this.data;



  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
  }
  ngOnInit() {
  }
}

When I run my app I get this error in html file , line 2:

ERROR TypeError: this.dataSource.connect is not a function

Here's html file :

<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource">

    <!-- Position Column -->
    <ng-container matColumnDef="text">
      <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.text}} </mat-cell>
    </ng-container>



    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>

Answer

Jeto picture Jeto · Mar 4, 2018

Refer to one of the examples from the docs.

You need to instantiate a MatTableDataSource this way:

dataSource = new MatTableDataSource(yourDataArray);

In your case, you can also add the type information:

dataSource = new MatTableDataSource<nomchamp>(yourDataArray);