数据表未显示我的数据源阵列

时间:2019-02-10 00:07:44

标签: angular-material angular5 datasource mat-table

我有一个问题,我不知道如何从我的组件中解决它,我发送了一个Resource数组,以便另一个组件读取它并将其注入到由mat-table读取的DataSource中。查阅了Angular的文档后,我发现它是正确的。我不知道它是否是html中不允许我看到的东西。有人可以告诉我原因吗?

非常感谢您

我的.ts

 @Input() resources : Resource [];

public dataSource = new MatTableDataSource <Resource> ();
public ngOnInit(): void {
        console.log(this.resources)
        this.dataSource.data = this.resources
   }

我的.html

<mat-table class="resources-table" #table [dataSource]="resources" matSort [@animateStagger]="{value:'50'}" fusePerfectScrollbar>

    <!-- ID Column -->
    <ng-container matColumnDef="_id">
        <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
        <mat-cell *matCellDef="let resource">
            <p class="text-truncate">{{resource._id}}</p>
        </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
        <mat-header-cell *matHeaderCellDef mat-sort-header>{{'RESOURCE.NAME' | translate}}</mat-header-cell>
        <mat-cell *matCellDef="let resource">
            <p class="text-truncate">{{resource.name}}</p>
        </mat-cell>
    </ng-container>
</mat-table>

console.log(this.resources)是img:

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试设置要在其中添加数据的Mat-Table的DataSource属性:

HTML代码:

                                    \/ <-- Here
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">

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

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

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

TS代码:

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

@Component({
  selector: 'table-sorting-example',
  styleUrls: ['table-sorting-example.css'],
  templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample implements OnInit {
  displayedColumns: string[] = ['_id', 'name'];
  dataSource = new MatTableDataSource([]);

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    var elements = [{ _id: 1, name: 'Paul Walker' },
    { _id: 2, name: 'Lisa' }];

    this.dataSource = new MatTableDataSource(elements); // Set dataSource  like this 
    this.dataSource.sort = this.sort; // and then assign sort
  }
}

Stackblitz