I'm trying to integrate Angular's material table in a new project but for some reason the data is not displayed, only the empty rows. I used the same logic in another project and there it works, I spent a lot of time to find the reason but nothing works.
I need to add the table in a lazy loaded module called "cores" and I imported the material table module:
import { MatTableModule } from '@angular/material';
imports: [
CommonModule,
CoresRoutingModule,
MatTableModule
]
I created a services which returns an array of "ICore" objects:
getCores(): Observable<ICore[]> {
return this.http.get<ICore[]>('/cores');
}
The ICore interface:
export interface ICore {
id: number;
name: string;
}
The HTML from my "index.component.html" file:
<mat-table [dataSource]="dataSource">
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef> Id </mat-header-cell>
<mat-cell *matCellDef="let core"> {{ core.id }}</mat-cell>
</ng-container>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell *matCellDef="let core"> {{ core.name }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
The logic from "index.components.ts" file:
dataSource = new MatTableDataSource<ICore>();
columnsToDisplay = ['id', 'name'];
constructor(private coreService: CoreService) { }
ngOnInit() {
this.coreService.getCores().subscribe(
res => {
this.dataSource.data = res;
console.log(this.dataSource);
},
err => console.log(err)
);
}
From my console.log I see that the dataSource is populated:
MatTableDataSource {_renderData: BehaviorSubject, _filter: BehaviorSubject, _internalPageChanges: Subject, _renderChangesSubscription: Subscriber, sortingDataAccessor: ƒ, …}
data: Array(3)
0: {id: 1, name: "core1"}
1: {id: 2, name: "core2"}
2: {id: 3, name: "core3"}
I also tried this method:
dataSource = new CoreDataSource(this.coreService);
columnsToDisplay = ['id', 'name'];
constructor(private coreService: CoreService) { }
export class CoreDataSource extends DataSource<any> {
constructor(private coreService: CoreService) {
super();
}
connect(): Observable<ICore[]> {
console.log(this.coreService.getCores());
return this.coreService.getCores(); }
disconnect() {} }
But with the same result. I feel that is something stupid that I forget to do but I don't find it.
Thanks in advance!
Make sure you use the same variable to display the columns that you defined in your component.
Component:
columnsToDisplay = ['id', 'name'];
Template:
<mat-header-row *matHeaderRowDef="columnsToDisplay"></mat-header-row>
<mat-row *matRowDef="let row; columns: columnsToDisplay;"></mat-row>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With