【问题标题】:Is there a way to add material select option at the end of the list?有没有办法在列表末尾添加材料选择选项?
【发布时间】:2020-02-26 16:20:03
【问题描述】:

每当我有一个 ,当我选择一个选项时,我想把它添加到列表的末尾,而不是把它作为它的顺序...

您可以检查材料的堆叠闪电战: https://stackblitz.com/angular/jdgkdlbeldj?file=src%2Fapp%2Fselect-multiple-example.ts

如果我有这个列表:

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

我最初选择 Mushroom and Pepperoni ->MyList = [Mushroom, Pepperoni].

如果我添加一个新选项,例如 Onion,我希望 MyList 为: [Mushroom, Pepperoni, Onion],但我得到的是[Mushroom, Onion, Pepperoni]

我该怎么做?

【问题讨论】:

    标签: html angular angular-material


    【解决方案1】:

    Angular 材质select 提供 sortComparator 输入属性。它将接受比较器功能对所选值进行排序。

    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

    【讨论】:

    • @EstebanChornet sortComparator 是接受 js 比较函数作为输入的输入属性,更多信息:w3schools.com/js/js_array_sort.asp
    • 所以我的component.ts 中真的不需要参数吗?只需 sortComparator() { return 1; } 因为我们强制总是返回 1...
    • 实际比较函数接收两个参数,如果第一个参数应该在第二个参数之前,则返回 1,如果第二个参数应该在第一个参数之前,则返回 -1,如果它们相等,则返回 0。
    【解决方案2】:

    而是使用表单绑定手动检查selectionChange 事件何时被触发,然后将新选择与您保存的选择进行比较。当您的列表中未选择新的选定元素时,当您的新选择中缺少项目时,将其推入其中,将其从列表中删除。

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

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 2020-11-10
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多