Option display in mat-select

1.3k Views Asked by At

I have 10 option in mat-select. I selected 10th option from drop-down. Now, again when I open drop down then it shows from 10th option. I want to display option from the top always.

1

There are 1 best solutions below

3
On

You can add some code, that will rearrange the list of options for you everytime when you select the new value

<form [formGroup]="form">
  <mat-form-field appearance="fill">
    <mat-label>Values</mat-label>
    <mat-select formControlName="value">
      <mat-option *ngFor="let item of options"
         [value]="item.id">{{ item.name }}</mat-option>
  </mat-select>
  </mat-form-field>
</form>


export class AppComponent  {
  name = 'Angular';
  form: FormGroup;

  options = [
    {
      id: 1,
      name: 'First'
    },
    {
      id: 2,
      name: 'Second'
    },
    {
      id: 3,
      name: 'Third'
    }
  ]

  constructor(
    private fb: FormBuilder,
  ){}

  ngOnInit(): void {
    this.form = this.fb.group({
      value: [null]
    });

    this.form.get('value').valueChanges.subscribe((value) => {
      const current = this.options.find(item => item.id === value);
      const filtered = this.options.filter(item => item.id !== value);

      this.options = [current].concat(filtered);
    });    
  }
}

link to stackblitz