DEV Community

Pantelis Papasavvas
Pantelis Papasavvas

Posted on • Updated on

Angular material table remove element by index with paginator

The easy way to implement this is to take the index of the row and apply the filter or the splice method to the dataSource.
Ideally we are going to create a click on the delete button and then we are going to get the row index. After that and with the row index we are going to filter the dataSource to exclude the record with the same index as the index that we get from the click event.
At this phase our code it will like look like this

this.dataSource.data = this.dataSource.data
  .filter(item, index => index !== selectedIndex );
Enter fullscreen mode Exit fullscreen mode

This works fine in all cases if we don’t have pagination on our material table.
So what happens in the case that we want to delete a record that it is on the second or the third page of the table and not in the first page?

The Problem

The problem is that, when we have pagination on the material table, the row Index starts from zero in every page. For example, the first element of the first page has index 0 and the first element of the second page has again index 0. Actually, every first element on every page has index equals to 0.

One solution to this is to follow the dataSource index.
So the only thing that we need to do is to calculate the index every time that we want to remove an element.
So from ngAfterViewInit we have available the table paginator

ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
}
Enter fullscreen mode Exit fullscreen mode

With this we have access in some properties that paginator has. The properties that we want here is the pageIndex and the pageSize.
Then we can calculate the rowIndex and will be

rowIndex + (pageIndex * pageSize)
Enter fullscreen mode Exit fullscreen mode

Now we can create a function like below to remove the record from our table

delelteRecord(){
 const { pageIndex, pageSize } = paginator;
 const removeIndex = parentIndex + (pageIndex * pageSize);
 return dataSource.data.filter((i, index) => index !== 
 removeIndex);
}
Enter fullscreen mode Exit fullscreen mode

Now the rowIndex will follow the dataSource index and we are ready to apply the filter method in our dataSource to get the new dataSource and display it to the screen.

Top comments (2)

Collapse
 
matoni1 profile image
Antonio Ribeiro

Great advice. Nice to find a dev encountering this issue and finding a way around it. My solution was a bit different. All i did was add an index value into the dataSource JS object. In other words a new Object key and value for every entry in the JS object. Then simply reference the entry in the material table by that value

Collapse
 
pantpapasavvas profile image
Pantelis Papasavvas

Thanks for your feedback Antonio.
I took benefit from paginator to solve my problem.
I like your solution as it is more simple than mine.