1
votes

I want to whenever I have a , when I choose an option, add it at the end of the list, instead of placing it as its order...

You can check material's stackblitz: https://stackblitz.com/angular/jdgkdlbeldj?file=src%2Fapp%2Fselect-multiple-example.ts

If I have this list:

toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];

And I select initially Mushroom and Pepperoni ->MyList = [Mushroom, Pepperoni].

If I add a new option, such as Onion, I would like to be having MyList as: [Mushroom, Pepperoni, Onion], but I get it as [Mushroom, Onion, Pepperoni].

How can I do it?

2

2 Answers

4
votes

Angular material select provide sortComparator input property. It will accept comparater fuction to sort the selected value.

component.html

<mat-form-field>
  <mat-label>Toppings</mat-label>
  <mat-select [sortComparator]="sortComparator" [formControl]="toppings" multiple>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
</mat-form-field>

component.ts

sortComparator(a:any, b:any){
    return 1;
  }

Example

1
votes

Instead using a form binding manually check when selectionChange event gets triggered and then compare the new selection with your saved selection. When a new selected element isn't selected in your list then push it into it when when in your new selection is an item missing remove this from your list.

<mat-form-field>
  <mat-select (selectionChange)="changeMySelection($event)" [value]="myList">
     // your options ....
  </mat-select>
</mat-form-field>