As a newcomer to Angular and Typescript, I've encountered a peculiar issue. When trying to populate a mat-table with values retrieved from a backend API, the data appears empty in my component but suddenly shows up when rendering the template.
Here's an example of my component:
import { Component, OnInit, ViewChild } from '@angular/core';
import { first } from 'rxjs/operators';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator, MatSort } from '@angular/material';
import { Invoice } from '../_models';
import { InvoiceService } from '../_services';
@Component({
selector: 'app-invoices',
templateUrl: './invoices.component.html',
styleUrls: ['./invoices.component.css']
})
export class InvoicesComponent implements OnInit {
displayedColumns=['rating', 'amount', 'debtor', 'serial', 'dateout', 'expiration', 'daysleft', 'fid']
invoices: Invoice[] = [];
dataSource= new MatTableDataSource<Invoice>(this.invoices);
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor(
private invoiceService: InvoiceService
) { }
ngOnInit() {
this.loadInvoices();
console.log(this.invoices);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
private loadInvoices(){
this.invoiceService.getUserInvoices().pipe(first()).subscribe(invoices => {
this.invoices=invoices;
});
console.log(this.invoices);
}
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filter = filterValue;
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
}
And here is a snippet from the template:
...
@foreach($invoices as $invoice)
...
@endforeach
...
The key point of concern lies in the usage of [dataSource]="invoices"
. Upon retrieving data via the loadInvoices method, the array remains empty. Switching it to [dataSource]="dataSource"
also results in an empty array. How can I effectively utilize the fetched data to initialize a MatTableDataSource object and pass it to the template?
With assistance from @DiabolicWords, the updated component code looks like this:
// Updated component code