Mat-selection-list selected coming first?

Viewed 270

If I have a mat-selection-list filled with mat-list-option, can I somehow put the selected values on top of the list?

                       <mat-selection-list formControlName="mySubEntityIds">
                          <mat-list-option [value]="entity.id" *ngFor="let entity of entities" checkboxPosition="before">
                             {{entity.name}}
                          </mat-list-option>
                       </mat-selection-list>
1 Answers

Essentially, you take the clicked item, remove it from its position and put it at the beginning of the entities array.

Not sure if your list is multi-selection, but here's the quick solution [assumption: id is unique]:

<mat-selection-list>
  <mat-list-option
    [value]="entity.id"
    *ngFor="let entity of entities"
    checkboxPosition="before"
    (click)="onSelected(entity.id)">
    {{ entity.name }}
  </mat-list-option>
</mat-selection-list>

and in ts:

onSelected(id){
    let removedItem;
    let removedIndex;
    this.entities.every( (element,i) => {
        if(element.id == id){
            removedItem = element;
            removedIndex = i;
            return false;
        }
        return true;
    });
    this.entities.splice(removedIndex,1);
    this.entities.unshift(removedItem);
}

Stackblitz example: https://stackblitz.com/edit/mat-selection-list-8zbx1j

Related