Reputation: 119
I have a project in angular, and have an angular material datatable. So, I want to fill it with data from a json. Because when I try to fill it simply nothing is showed, as if empty, but if I fill the datatable with static data, it shows the data. The idea is filling the datatable with data from json.
Upvotes: 2
Views: 4875
Reputation: 1815
Please check this, hope it will help you:
this.http.get('servieurl').subscribe(data =>
{
this.apps.push(data);
this.displayedColumns = ['columnName'];
this.dataSource = new MatTableDataSource(this.apps);
}, error => console.error(error));
Html:
<table mat-table [dataSource]="dataSource">
...
</table>
For more check this link : fill an angular material datatable with data from a json?
Upvotes: 1
Reputation: 39432
You'll need to instantiate MatTableDataSource
with the data that you get from your service.
dataSource;
data;
ngOnInit() {
this.yourService.getData()
.subscribe((data: Type[]) => {
this.data = data;
this.dataSource = new MatTableDataSource(data);
});
}
And then in your template, use this:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
...
</table>
Note here that the responsibility of getting the data from the backend is of the Service and you'll just call a method on it to get the data.
Here's a Sample StackBlitz for your ref. In here, I'm getting the users list from JSONPlaceholder API and then showing it on the template by setting its dataSource
Upvotes: 3