Shubham Kumar Keshri
Shubham Kumar Keshri

Reputation: 33

Option display in mat-select

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.

Upvotes: 0

Views: 1442

Answers (1)

Slawa Eremin
Slawa Eremin

Reputation: 5415

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

Upvotes: 0

Related Questions