Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mat-selection-list with search filter not keeping selections after a search

I'm attempting to implement a mat-selection-list to have a list of characters--but at the top, you can search/filter characters. This is working except when you select a character, search for another character, then stop searching--your original selection is visible in the UI, but the model is cleared until you make another selection.

Example of what I mean: https://stackblitz.com/edit/angular-yo2o9o

I can come up with a way to fix this--by manually pushing/removing from an array; but this doesn't keep the order selected in the list and that's important.

Any ideas how this can be solved without some gross workaround?

like image 264
Nxt3 Avatar asked Sep 18 '25 13:09

Nxt3


1 Answers

Don't use ngModel and ngModelChange - use selectionChange and manage the model yourself. To manage the ordering problem, just filter the original array instead of pushing/removing:

<mat-selection-list #heroes
        (selectionChange)="onSelectedOptionsChange()"
        [disableRipple]="true">
    <mat-list-option *ngFor="let hero of (overwatchHeroes | heroSearch:heroSearch.value)"
            (click)="hero.selected = !hero.selected;"
            [selected]="hero.selected"
            [value]="hero">
        {{hero.name}} - {{hero.selected}}
    </mat-list-option>
</mat-selection-list>

public onSelectedOptionsChange() {
    setTimeout(() => {
        this.selectedLongListHeroes = this.overwatchHeroes.filter(hero => {
            return hero.selected; 
        });
    })
}
like image 73
G. Tranter Avatar answered Sep 21 '25 02:09

G. Tranter