Reputation: 753
I'm trying to implement a table component from angular material component and all good and look nice, the big problem is how to populate the table with dynamic data from DB. I receive from DB a object array like in this example but I really don't know how to iterate this and to populate my table.
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’}
];
here is an example with the table component:
https://stackblitz.com/angular/dnbermjydavk?file=app%2Ftable-overview-example.ts
So how can I populate this table with this kind of array objects.
Thank's in advance !
Upvotes: 2
Views: 394
Reputation: 2680
so, as as per your requirement, Lets pass the data as you are getting , In Array Format
[
{id: "1", name: "Jimmy", progress: "10", color: "blue"},
{id: "2", name: "John", progress: "40", color: "yellow"},
{id: "3", name: "Wright", progress: "70", color: "orange"}
]
removing %
as its appending From HTML, You can Just Remove it from
table-overview-example.html
Line:20
(Have a look here)
pass the array inside here: MatTableDataSource()
like below:
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'];
Here is a working Demo.
Upvotes: 3