1

我在 mat-select 中有 10 个选项。我从下拉列表中选择了第 10 个选项。现在,当我再次打开下拉菜单时,它会从第 10 个选项显示。我想始终从顶部显示选项。

4

1 回答 1

0

options您可以添加一些代码,每次选择新值时都会为您重新排列列表

<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);
    });    
  }
}

链接到stackblitz

于 2022-03-04T19:47:22.860 回答