Search code examples
angularangular-materialangular7angular-cdk

Multi-select with cdk-virtual-for making it look like nothing was selected


I have a couple of angular material multi-selects that are utilizing the new Virtual for in the CDK.

When you select a couple of items and scroll them out of view, thus dropping them from the virtual for and then close the select, it looks like the inputs were dropped, but when opening up the select and scrolling back up you see they are still selected.

Here is an imgur album displaying my issue: https://i.sstatic.net/1Pm7a.jpg

The only workaround I've been able to come up with is that I can detect when the select is closed and reorder the selected items to the top of the list, as well as rest the virtual scroll.


Solution

  • So I ended up finding the solution to this issue, using a container that contains the selected form options

    Apply this in the HTML, at the bottom of the mat-select:

    <ng-container *ngIf="isMultiple">
        <mat-option class="selected-options" *ngFor="let option of 
        this.form.value[control]" value="{{option}}">{{option}}</mat-option>
    </ng-container>
    <ng-container *ngIf="!isMultiple">
        <mat-option class="selected-options" *ngIf="this.form.value[control]" 
        value=" . 
        {{this.form.value[control]}}">{{this.form.value[control]}}</mat-option>
    </ng-container> 
    

    css:

    .selected-options{
      visibility: hidden;
      position: absolute;
    }
    

    Credit to danderwald on this github issue: https://github.com/angular/material2/issues/13087