【问题标题】:Angular order of selected option in multiple mat-select多个垫选择中所选选项的角度顺序
【发布时间】:2022-11-23 16:25:23
【问题描述】:

我希望能够跟踪多个 mat-select 中所选选项的顺序。我怎样才能实现这个用例?

假设我先选择“洋葱”,然后选择“蘑菇”,然后选择“意大利辣香肠”。我希望能够从 mat-select 中按此顺序选择所选选项 ['Onion', 'Mushroom', 'Pepperoni']。 如果我然后取消选择“蘑菇”并选择“额外奶酪”,我想在数组中获取所选选项,如 ['洋葱'、'意大利辣香肠'、'额外奶酪']。

【问题讨论】:

  • 这取决于您如何绑定项目。如果你通过 formControl 设置它,我会使用 valuechanges 如果它的模板绑定我会使用 ngOptionChanged 如果没有这些我会使用 selectionChanged 从 mat-select 它自己。授予所有提及将为您提供所有选定的项目。所以你必须编写逻辑来查找列表中最新添加的内容并将它们添加到变量中。同样,如果删除了任何内容,请将其从该变量中删除。

标签: angular angular-material dropdown mat-select


【解决方案1】:

我建议使用FormControl

在你的中创建FormControl组件.ts

toppings = new FormControl('');
toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];

然后将它绑定在你的 mat-select 中组件.html

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

或者,

你也可以在你的mat-select中添加(selectionChange)=selectionChanged($event)

<mat-select [formControl]="toppings" (selectionChange)=selectionChanged($event) multiple>

【讨论】:

  • 问题不是如何绑定数据,而是跟踪选择的顺序。
猜你喜欢
  • 1970-01-01
  • 2021-01-29
  • 2020-10-18
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 2018-08-21
  • 2021-10-21
  • 2012-09-05
相关资源
最近更新 更多