Building a generic data-table component in angular 5 with material 5
We will be building a generic data-table component, as the name says, it is a table that displays any set of data in a nice tabular format and the way it is generic is, it is configurable, where to get the data from and what to display.
The idea is to simplify the usage of mat-table by creating a custom component that takes just the ‘path’ and the required ‘columns’ to be displayed.No more touching the ts code to manage your columns, or no need to duplicate the component logic for every mat-table you put in your application.We should be able to just drop the 2 liner html code where ever you need to display a table in your application.
This is how it should look
I will be using Awesome StackBlitz code editor, it’s much easier to manage dependencies and faster. You can get started with a simple starter application and then you can edit/add/delete files per your needs.
Now, create a directory to hold all your generic services, i call it services, and create an api.service.ts file in it.
This is how a simple api.service.ts look like
Then head to data-table.component.ts and configure your data source and hook up your api service
Notice i’m not hooking up the apiService in the constructor but in the ngOnInit() method, this is because @Input() path won’t be available during its construction and so ‘this.path’ will be undefined. and we have one more class called MyDataSource that extends DataSource from @angular/cdk/collections. we just need to override two methods here connect() and disconnect(), that takes care of connecting to our data source and returning the subject as observable. It is a good practise to return the subject as observable rather than directly exposing the subject.
We then initialise a new instance of data source in ngOnInit() and pass this.dataSubject (which is a behavior subject — A subject whose behavior/value changes over time), As you can see there is no direct link in the code where we set each of elements of the response to ‘this.dataSource’, but rather, we subscribe to apiService.getData method which returns data asynchronously over time, as and when the data is received, it is sent to ‘this.dataSource’ in the form of an observable.
Now the final part, creating a html markup that will be generated based on the values from the dataSource.
That’s it. Thanks for reading! Full source code is available on StackBlitz and Github.