关于angular:在mat-select内显示一个mat-icon,并使用mat-select-trigger显示两者

Display a mat-icon inside mat-select and display both as selected using mat-select-trigger

我正在Angular 7中工作,我的要求之一是使用mat-icons创建mat-select。我面临的问题是我要么可以显示图标,要么可以显示选项标签,但不能同时显示两者。我需要做的是能够链接值,但是尝试时出现错误。

将垫选设置为-

1
2
3
4
5
6
7
8
9
    <button mat-raised-button type="button" name="button" color="primary" class="roundedButton">
    <mat-select [(value)]="selected2">
      <mat-select-trigger><mat-icon>{{selected2}}</mat-icon>{{selected2}}</mat-select-trigger>
      <mat-option *ngFor="let food of foods" [value]="food.value">
        <mat-icon>{{food.icon}}</mat-icon>{{food.viewValue}}
      </mat-option>
    </mat-select>
    </button>
</mat-form-field>

我已将所选图标和标签放置在mat-select-trigger中,并将值设置为food.value。

用于选择的界面是

1
2
3
4
5
export interface Food {
  value: string;
  viewValue: string;
  icon: any;
}

并将选择选项设置为

1
2
3
4
5
6
  foods: Food[] = [
    {value: 'steak-0', icon: 'add', viewValue: 'Steak'},
    {value: 'pizza-1', icon: 'lock', viewValue: 'Pizza'},
    {value: 'tacos-2', icon: 'search', viewValue: 'Tacos'}
  ];
    public selected2 = 'steak-0';

如果我将值更改为food.icon,则可以显示选择选项图标作为选择。如果将value更改为food.viewValue,则会显示该选项的标签。

当用户进行选择时,如何获得两者?

我已经设置了Stackblitz,以显示实际的设置和问题。

提前谢谢!


而不是将值设置为iconviewValue,而是将其设置为整个对象。这样,所选值将包含整个对象中的数据。然后,您可以简单地使用所选对象中的属性来获取所需的内容。

1
2
3
4
5
6
7
8
9
10
<mat-form-field>
    <button mat-raised-button type="button" name="button" color="primary" class="roundedButton">
        <mat-select [(value)]="selected2" [compareWith]="compareFn">
            <mat-select-trigger><mat-icon class="selection-icon">{{selected2.icon}}</mat-icon><span>{{selected2.viewValue}}</span></mat-select-trigger>
            <mat-option *ngFor="let food of foods" [value]="food">
                <mat-icon>{{food.icon}}</mat-icon>{{food.viewValue}}
            </mat-option>
        </mat-select>
    </button>
</mat-form-field>

现在iconviewValue都将显示在选择触发器中。您只需要图标的css,因为它不会与viewValue内联。

1
2
3
4
5
.selection-icon {
    position: relative;
    top: 6px;
    margin-right: 16px;
}

这是一个可行的示例。

注意:为了设置此选定对象的值,您可以传递原始数组本身中的一个对象(例如public selected2 = foods[0]),也可以使用compareWith来使select为能够跟踪值,因为我们的选项value是一个对象。这类似于ngFor中的trackBy。基本上,要么传递原始数组的引用,以便select可以对其进行跟踪,要么使用compareWith告诉select基于每个对象中的某些唯一值来跟踪数组中的对象。


您可以尝试以下代码:

1
2
3
4
5
6
<mat-select #select>
  <mat-select-trigger *ngIf="select.value"><mat-icon>{{select.value.icon}}</mat-icon>{{select.value.viewValue}}</mat-select-trigger>
  <mat-option *ngFor="let food of foods" [value]="food">
    <mat-icon>{{food.icon}}</mat-icon>{{food.viewValue}}
  </mat-option>
</mat-select>