148

I am new in angular 5 development. I am trying to develop a data table with angular material using the example provided here: "https://material.angular.io/components/table/examples".

I am getting an error saying Can't bind to 'dataSource' since it isn't a known property of 'table'.

enter image description here

Please help.

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Rahul Munjal
  • 2,551
  • 2
  • 15
  • 35

21 Answers21

217

Remember to add MatTableModule in your app.module's imports i.e.

In Angular 9+

import { MatTableModule } from '@angular/material/table'  

@NgModule({
  imports: [
    // ...
    MatTableModule
    // ...
  ]
})

Less than Angular 9

import { MatTableModule } from '@angular/material'  

@NgModule({
  imports: [
    // ...
    MatTableModule
    // ...
  ]
})
WasiF
  • 26,101
  • 16
  • 120
  • 128
53

Thanx to @Jota.Toledo, I got the solution for my table creation. Please find the working code below:

component.html

<mat-table #table [dataSource]="dataSource" matSort>
  <ng-container matColumnDef="{{column.id}}" *ngFor="let column of columnNames">
    <mat-header-cell *matHeaderCellDef mat-sort-header> {{column.value}}</mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element[column.id]}}</mat-cell>
  </ng-container>

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

component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource, MatSort } from '@angular/material';
import { DataSource } from '@angular/cdk/table';

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

  dataSource;
  displayedColumns = [];
  @ViewChild(MatSort) sort: MatSort;

  /**
   * Pre-defined columns list for user table
   */
  columnNames = [{
    id: 'position',
    value: 'No.',

  }, {
    id: 'name',
    value: 'Name',
  },
    {
      id: 'weight',
      value: 'Weight',
    },
    {
      id: 'symbol',
      value: 'Symbol',
    }];

  ngOnInit() {
    this.displayedColumns = this.columnNames.map(x => x.id);
    this.createTable();
  }

  createTable() {
    let tableArr: Element[] = [{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
      { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
      { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
      { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
      { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
      { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
    ];
    this.dataSource = new MatTableDataSource(tableArr);
    this.dataSource.sort = this.sort;
  }
}

export interface Element {
  position: number,
  name: string,
  weight: number,
  symbol: string
}

app.module.ts

imports: [
  MatSortModule,
  MatTableModule,
],
WasiF
  • 26,101
  • 16
  • 120
  • 128
Rahul Munjal
  • 2,551
  • 2
  • 15
  • 35
  • 3
    Using this I can make reusable table component which takes data array and columnNames array. This is far better solution than examples in https://material.angular.io – Janne Harju Oct 15 '18 at 05:53
18
  • Angular Core v6.0.2,
  • Angular Material, v6.0.2,
  • Angular CLI v6.0.0 (globally v6.1.2)

I had this issue when running ng test, so to fix it, I added to my xyz.component.spec.ts file:

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

And added it to imports section in TestBed.configureTestingModule({}):

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
      declarations: [ BookComponent ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
}));
Sunil Singh
  • 11,001
  • 2
  • 27
  • 48
Andrii Lundiak
  • 181
  • 1
  • 3
14

if your "import { MatTableModule } from '@angular/material';" is on a shared module, make sure you export it.

sharedmodule.ts:

import { MatTableModule } from '@angular/material' 

@NgModule({
  imports: [
    // ...
    MatTableModule
    // ...
  ],
  exports:[ MatTableModule ]
})

then on your custom module where you define the component that use material table:

custommodule.ts:

@NgModule({
imports: [ sharedmodule ]     
})
The_Rub
  • 141
  • 1
  • 3
10

Material example is using the wrong table tags. Change

<table mat-table></table>
<th mat-header-cell></th>
<td mat-cell></td>

<tr mat-header-row></tr>
<tr mat-row></tr>

to

<mat-table></mat-table>
<mat-header-cell></mat-header-cell>
<mat-cell></mat-cell>

<mat-header-row></<mat-header-row>
<mat-row></<mat-row>
itzhar
  • 12,743
  • 6
  • 56
  • 63
9

For Angular 7

Check where is your table component located. In my case it was located like app/shared/tablecomponent where shared folder contains all sub components But I was importing material module in Ngmodules of app.module.ts which was incorrect. In this case Material module should be imported in Ngmodules of shared.module.ts And it works.

There is NO NEED to change 'table' to 'mat-table' in angular 7.

Angular7 - Can't bind to 'dataSource' since it isn't a known property of 'mat-table'

Sanchit
  • 109
  • 1
  • 4
5

In my case the trouble was I didn't put the components that contain the datasource in the declarations of main module.

NgModule({
  imports: [
    EnterpriseConfigurationsRoutingModule,
    SharedModule
  ],
  declarations: [
    LegalCompanyTypeAssignComponent,
    LegalCompanyTypeAssignItemComponent,
    ProductsOfferedListComponent,
    ProductsOfferedItemComponent,
    CustomerCashWithdrawalRangeListComponent,
    CustomerCashWithdrawalRangeItemComponent,
    CustomerInitialAmountRangeListComponent,
    CustomerInitialAmountRangeItemComponent,
    CustomerAgeRangeListComponent,
    CustomerAgeRangeItemComponent,
    CustomerAccountCreditRangeListComponent, //<--This component contains the dataSource
    CustomerAccountCreditRangeItemComponent,
  

  ],

The component contains the dataSource:

export class CustomerAccountCreditRangeListComponent implements OnInit {

  @ViewChild(MatPaginator) set paginator(paginator: MatPaginator){
    this.dataSource.paginator = paginator;
  }
  @ViewChild(MatSort) set sort(sort: MatSort){
    this.dataSource.sort = sort;
  }

  dataSource = new MatTableDataSource(); //<--The dataSource used in HTML
  loading: any;
  resultsLength: any;
  displayedColumns: string[] = ["id", "desde", "hasta", "tipoClienteNombre", "eliminar"];
  data: any;

  constructor(
    private crud: CustomerAccountCreditRangeService,
    public snackBar: MatSnackBar,
    public dialog: MatDialog,
    private ui: UIComponentsService
  ) {
  }

This is for Angular 9

Aly González
  • 51
  • 2
  • 6
4

I imported MatTableModule in app-routing module and the error was gone.

3

I was also breaking my head for a long time with this error message and later I identified that I was using [datasource] instead of [dataSource].

Balasubramanian S
  • 1,345
  • 12
  • 16
  • Thanks for this! I had the same issue with a pug converter online from: https://html-to-pug.com/, it copied the **[dataSource]** input and converted it to **[datasource]** – Jonathan002 May 26 '20 at 07:17
2

I had the same issue! Although I rectified it my adding the import of MatTableModule into the mycustom module.ts , instead of adding it in app.module.ts

Note: As I have created a custom module(inbox.module.ts) and created components in it, hence the declarations of those modules were created in inbox.module.ts, due to which the import of MatTableModule was suppose to be done in inbox.module.ts and not in app.module.ts

2

In my case, I was adding MatTableModule in the app module, but I have nested components like so:

app module
|__________dashboard module
           |_________________user module
                             |___________plans module

I added MatTableModule in the direct parent of plans module which is user module, then it worked.

HibaHasan
  • 1,255
  • 2
  • 5
  • 12
1

For those who just use the Angular CDK and not Angular Material, instead of importing MatTableModule import CdkTableModule:

import { CdkTableModule } from '@angular/cdk/table';

@NgModule({
imports: [
    ...
    CdkTableModule,
    ...
],
Kheder
  • 203
  • 3
  • 9
1

Once on my angular 13, I have got this same issue because I forgot to add my component in the app module in which I have imported MatTableModule.

1

For me the problem was very strange, but I could reproduce it, which means it could happen to other people.

My Angular version was 14. When I wanted to add Material to my project with ng add @angular/material the material version it wanted to install, and asked me was 7.0.0 (which I missed and installed anyway).

When I had taken a look at other projects, their material version was much higher: 14.2.6.

In the end what solved the issue for me was giving a specific angular material version for the ng add command. You'll have to check what your current version is and add that to the command. For example:

ng add @angular/material@14.2.6
CaptainCsaba
  • 266
  • 2
  • 12
1

Step 1 : open -> app.module.ts

Step 2 : import below

import { MatTableModule } from '@angular/material/table'

Step 3: And under import add MatTableModule as below

@NgModule({
  imports: [
     
   MatTableModule
    
  ]
})

Below is the screenshot to refer:

enter image description here

desertnaut
  • 57,590
  • 26
  • 140
  • 166
0

Remember to import the MatTableModule module and remove the table element show below for reference.
wrong implementation
<table mat-table [dataSource]=”myDataArray”> ... </table>
correct implementation:
<mat-table [dataSource]="myDataArray"> </mat-table>

Yogesh Aggarwal
  • 994
  • 7
  • 9
0

The problem is your angular material version, I have the same, and I have resolved this when I have installed the good version of angular material in local.

Hope it solve yours too.

Andresse Njeungoue
  • 608
  • 1
  • 5
  • 19
0

I have resolved it by change [data-source]="dataSource" to [dataSource]="dataSource" in my name.component.html

0

I have separate modules for each feature and adding the feature module that contained the MatTableModule in the app.module has fixed it.

Naod Agere
  • 39
  • 1
  • 6
-1

If you've tried everything mentioned here and it didn't work, make sure you also have added angular material to your project. If not, just run the following command in the terminal to add it:

ng add @angular/material

After it successfully gets added, wait for the project to get refreshed, and the error will be automatically gone.

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
-4

Please see your dataSource varibale doesn't get the data from the server or dataSource is not assigned to the expected format of data.

Omkar Jadhav
  • 656
  • 1
  • 5
  • 18