【发布时间】:2019-01-14 06:52:44
【问题描述】:
如何在 Angular Material DataTable 中传递我的 API 服务数据。我想渲染我的数据而不是这个静态数组。如果我像*ngFor="let item of service.list" 这样渲染我的数据,那么数据会被加载,但分页和排序不起作用。请给出一些解决方案或示例。
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';
export interface PeriodicElement {
name: string;
position: number;
weight: number;
symbol: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{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'}
];
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
}
【问题讨论】:
-
你为什么使用
*ngFor?必须是mat-table [dataSource]="service.list" -
查看此演示以获得帮助,stackblitz.com/edit/…
-
我的数据已加载,但问题是排序和分页不起作用@john