How can I maintain selections of 'mat-list-option' within 'cdk-virtual-scroll-viewport?

Discussão em 'Angular' iniciado por Timuçin Çiçek, Fevereiro 27, 2025.

  1. I have an implementation of mat-list-option to be used inside cdk-virtual-scroll-viewport. The actual project I'm working on is based on Angular 14. However, to achieve this implementation, I found a demo project in Angular 11.

    In this demo project, scrolling works great, and selections of each item are remembered on each scroll as expected.

    However, the same approach for Angular 14 doesn't work as expected. After a selection and scrolling, the selection is gone.

    Below is the HTML template to give you an idea of my implementation. The selectionChange binding handles each selection and calls the select and deselect methods of the SelectionModel, which you can find in the .ts file

    <mat-selection-list (selectionChange)="onSelectionChange($event)">
    <cdk-virtual-scroll-viewport [itemSize]="20" class="example-viewport">
    <mat-list-option
    *cdkVirtualFor="let item of list;"
    [value]="item"
    [selected]="selection.isSelected(item)"
    >{{item}}
    </mat-list-option>
    </cdk-virtual-scroll-viewport>
    </mat-selection-list>


    Below, you can find the .ts file, which includes the SelectionModel object to interact with the mat-selection list, handle selections, the list variable to manage lots of dummy items, and the onCheckboxChange method used for the selectionChange output binding:

    selection = new SelectionModel(true);
    list = Array.from(Array(10000).keys());

    onCheckboxChange(selection: MatSelectionListChange) {
    const changedOptions = selection.options;
    for (const option of changedOptions) {
    if (option.selected) {
    this.selection.select(option.value);
    } else {
    this.selection.deselect(option.value);
    }
    }
    }


    I have conducted extensive research and used ChatGPT to solve the issue here, but I couldn't find anything useful. Can you help me make this work as expected in an up-to-date Angular version?

    Here you can find the Stackblitz examples of each implementation and Angular version.

    Angular 11 (Demo working as Expected) : https://stackblitz.com/edit/virtual...awp4?file=src/app/list-selection-example.html

    Angular 14 (Not working as Expected) : https://stackblitz.com/edit/angular-b3c9dv-v3pya1?file=src/app/datepicker-overview-example.ts

    Continue reading...

Compartilhe esta Página