我试图从角度材质组件实现一个表组件并且一切都很好并且看起来不错,最大的问题是如何使用来自DB的动态数据填充表。 我从DB收到一个像这个例子中的对象数组,但我真的不知道如何迭代这个并填充我的表。
tablePopulate = [
{id: ‘1’, name: ‘Jimmy’, progress: ’10%’, color: ‘blue’},
{id: ‘2’, name: ‘John’, progress: ’40%’, color: ‘yellow’},
{id: ‘3’, name: ‘Wright’, progress: ’70%’, color: ‘orange’}
];
这是表组件的示例:
https://stackblitz.com/angular/dnbermjydavk?file=app%2Ftable-overview-example.ts
那么如何使用这种数组对象填充此表。
提前感谢!
答案 0 :(得分:3)
所以,根据您的要求, 让我们按照你的方式传递数据,采用数组格式
[
{id: "1", name: "Jimmy", progress: "10", color: "blue"},
{id: "2", name: "John", progress: "40", color: "yellow"},
{id: "3", name: "Wright", progress: "70", color: "orange"}
]
删除%
作为其附加内容从HTML中,您可以将其从中删除
table-overview-example.html
行:20
(看看here)
在这里传递数组:MatTableDataSource()
如下所示:
import {Component, ViewChild} from '@angular/core';
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';
/**
* @title Data table with sorting, pagination, and filtering.
*/
@Component({
selector: 'table-overview-example',
styleUrls: ['table-overview-example.css'],
templateUrl: 'table-overview-example.html',
})
export class TableOverviewExam ple {
displayedColumns = ['id', 'name', 'progress', 'color'];
dataSource: MatTableDataSource<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor() {
// Assign the data to the data source for the table to render
this.dataSource = new MatTableDataSource([
{id: "1", name: "Jimmy", progress: "10", color: "blue"},
{id: "2", name: "John", progress: "40", color: "yellow"},
{id: "3", name: "Wright", progress: "70", color: "orange"}
]);
}
/**
* Set the paginator and sort after the view init since this component will
* be able to query its view for the initialized paginator and sort.
*/
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filter = filterValue;
}
}
/** Constants used to fill up our data base. */
const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];
这是一个有效的Demo。