Angular 7 - Virtual scrollbar resets the selected item in multiselect while scrolling

Discussão em 'Angular' iniciado por Gauravsa, Fevereiro 27, 2025.

  1. Gauravsa

    Gauravsa Guest

    I have a multi select drop down with virtual scrollbar inside it.

    Html

    <mat-form-field>
    <mat-label>Toppings</mat-label>
    <mat-select [formControl]="multiSelectControl" multiple [(value)]="selected" (openedChange)="openChange($event)">
    <cdk-virtual-scroll-viewport itemSize="5" minBufferPx="200" maxBufferPx="400" [style.height.px]=5*48>
    <button (click)="selectAll()">Select All</button>
    <button (click)="clear()">Clear</button>
    <mat-option *cdkVirtualFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
    </cdk-virtual-scroll-viewport>
    </mat-select>
    </mat-form-field>


    The .ts file:

    export class AppComponent {
    title = 'test-proj';

    toppings = new FormControl();
    toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
    selected: any;

    @ViewChild(CdkVirtualScrollViewport)
    cdkVirtualScrollViewPort: CdkVirtualScrollViewport;

    multiSelectControl = new FormControl();

    constructor() {
    for (let i = 0; i < 4000; i++) {
    this.toppingList.push('gjkgkf--' + i);
    }
    }

    selectAll() {
    this.selected = this.toppingList;
    this.multiSelectControl.patchValue(this.toppingList);
    }

    clear() {
    this.selected = [];
    this.multiSelectControl.patchValue([]);
    }

    openChange($event: boolean) {
    if ($event) {
    this.cdkVirtualScrollViewPort.scrollToIndex(0);
    this.cdkVirtualScrollViewPort.checkViewportSize();
    }
    }


    I have added 4000 items in the dropdown. If I select the first 2 items and the last two items and scrolls, then the selection check on the first two items disappears.

    Please suggest. Thanks

    Continue reading...

Compartilhe esta Página