diprokon / ng-table-virtual-scroll

Virtual Scroll for Angular Material Table
https://diprokon.github.io/ng-table-virtual-scroll
MIT License
134 stars 42 forks source link

Array index is not showing the correct position in the array #46

Closed lesterlpena closed 3 years ago

lesterlpena commented 3 years ago

@diprokon thanks for the library, is very useful.

I am trying to use the variable index inside the loop but the count gets reset every time after scrolling. This is an example of the behavior : https://stackblitz.com/edit/angular-material-virtual-scrolling

Please let me know if can provide any help. Thank you again.

diprokon commented 3 years ago

Hi!

Unfortunately, the directive provides only limited slice of data rows for a table. Because of this, you have such behavior.

You can try to extend your Datasource, so every row will have index value (as you set id in your example)

lesterlpena commented 3 years ago

Ok

rvalimaki commented 1 year ago

Extending Datasource is not an option, I am afraid, because sorting and filtering will break original indices anyway. But I just wonder if we could have an offset of number of hidden rows before the current position. Then the offset + index would be the correct index we need for eg. drag & drop and other functionality.

guyyst commented 6 months ago

Old issue, but I figured I'd leave this here: I solved this by just adding cdkVirtualScrollViewport.getRenderedRange().start to the current index.

Create a pipe to convert the index:

@Pipe({
    name: 'virtualScrollIndex',
})
export class VirtualScrollIndexPipe implements PipeTransform {
    transform(index: number, scrollViewport: CdkVirtualScrollViewport) {
        return index + scrollViewport.getRenderedRange().start;
    }
}

And call it inside the table:

<cdk-virtual-scroll-viewport #scrollViewport>
    <table>
        <ng-container matColumnDef="position">
            <td mat-cell *matCellDef="let element; let i = index">
                {{ i | virtualScrollIndex: scrollViewport }}
            </td>
        </ng-container>
    </table>
</cdk-virtual-scroll-viewport>

By using a pipe triggered by the changing index the function gets called for every item on every scroll event. Which is a lot better than just calling getRenderedRange() in the HTML directly and getting called on every single change detection.