I'm facing an issue while trying to populate a Material Table with data.
My model Block
has fields such as id
, date
, etc. The API call is made in data.service
and the function getAllBlock()
fetches the blocks. I tested this in the app.component.html
file and it worked fine.
document-list.component.ts
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { DataService } from '../data.service';
import { Block } from '../models/block.model';
@Component({
selector: 'app-document-list',
templateUrl: './document-list.component.html',
styleUrls: ['./document-list.component.sass']
})
export class DocumentListComponent implements OnInit {
blocks: Block[];
//DataSource and columns for DataTable
displayedColumns: string[] = ['Id', 'Date', 'Data', 'Hash', 'PreviousHash'];
dataSource = new MatTableDataSource<Block>(this.blocks);
//Filter (search)
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
constructor(private dataService: DataService) { }
ngOnInit(){
return this.dataService.getAllBlock()
.subscribe(data => this.blocks = data);
}
}
document-list.component.html
<div class="content-table">
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- ID Column -->
<ng-container matColumnDef="Id">
<th mat-header-cell *matHeaderCellDef>ID</th>
<td mat-cell *matCellDef="let element"> {{element.Id}} </td>
</ng-container>
<!-- Date Column -->
<ng-container matColumnDef="Date">
<th mat-header-cell *matHeaderCellDef>Timestamp</th>
<td mat-cell *matCellDef="let element"> {{element.Date}} </td>
</ng-container>
<!-- Data Column -->
<ng-container matColumnDef="Data">
<th mat-header-cell *matHeaderCellDef>Data</th>
<td mat-cell *matCellDef="let element"> {{element.Data}} </td>
</ng-container>
<!-- Hash Column -->
<ng-container matColumnDef="Hash">
<th mat-header-cell *matHeaderCellDef>Hash</th>
<td mat-cell *matCellDef="let element"> {{element.Hash}} </td>
</ng-container>
<!-- Previous Hash -->
<ng-container matColumnDef="PreviousHash">
<th mat-header-cell *matHeaderCellDef>PrevHash</th>
<td mat-cell *matCellDef="let element"> {{element.PreviousHash}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
I need assistance on how to add data to the table successfully. Can someone guide me on what might be going wrong with my implementation?