Angular Material Data Table No Data

2019-08-21 07:49发布

I am trying angular 5 material data table.

It is showing the headings but no data is showing in the table.

I have copied this code from a site. On they showed that data is showing. I check everything and there is no difference in the code.

test.component.ts

import { Component, OnInit } from '@angular/core';
import {MatTableDataSource} from '@angular/material';

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

  displayedColumns = ['position', 'firstName', 'lastName', 'email'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);

  constructor() { }

  ngOnInit() {

  }

}

export interface Element {
  position: number;
  firstName: string;
  lastName: string;
  email: string;
}

const ELEMENT_DATA: Element[] = [
  {position: 1, firstName: 'John', lastName: 'Doe', email: 'john@gmail.com'},
  {position: 1, firstName: 'Mike', lastName: 'Hussey', email: 'mike@gmail.com'},
  {position: 1, firstName: 'Ricky', lastName: 'Hans', email: 'ricky@gmail.com'},
  {position: 1, firstName: 'Martin', lastName: 'Kos', email: 'martin@gmail.com'},
  {position: 1, firstName: 'Tom', lastName: 'Paisa', email: 'tom@gmail.com'}
];

test.component.html

<mat-table #table [dataSource]="dataSource">
    <ng-container matColumnDef="position">
          <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
          <mat-cell *matCellDef="let element">  </mat-cell>
        </ng-container>

        <ng-container matColumnDef="firstName">
          <mat-header-cell *matHeaderCellDef> First Name </mat-header-cell>
          <mat-cell *matCellDef="let element">  </mat-cell>
        </ng-container>

        <ng-container matColumnDef="lastName">
          <mat-header-cell *matHeaderCellDef> Last Name </mat-header-cell>
          <mat-cell *matCellDef="let element">  </mat-cell>
        </ng-container>

        <ng-container matColumnDef="email">
          <mat-header-cell *matHeaderCellDef> Email </mat-header-cell>
          <mat-cell *matCellDef="let element">  </mat-cell>
        </ng-container>

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

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-21 08:35

You need to set the datasource as follows,

 <mat-table #table [dataSource]="dataSource">

EDIT

DEMO

查看更多
登录 后发表回答