在 mat-select 内显示一个 mat-icon ,并使用 mat-select-trigger 将两者显示为选中



我在 Angular 7 中工作,我的要求之一是创建一个带有垫子图标的垫子选择。我遇到的问题是,我可以显示图标,也可以显示选项标签,但不能同时显示两者。我需要做的是能够链接值,但是当我尝试时我遇到了错误。

垫子选择设置如下-

<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>

我已将选定的图标和标签放置在垫子选择触发器中,并将值放置到食物值中。

选择的界面是

export interface Food {
value: string;
viewValue: string;
icon: any;
}

并且选择选项设置为

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,我可以让选择选项图标显示为选择。如果我将值更改为food.viewValue,我会得到要显示的选项的标签。

当用户做出选择时,如何同时获得两者?

我已经设置了一个堆栈闪电战来显示设置和问题的实际效果。

提前谢谢你!

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

<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内联显示。

.selection-icon {
position: relative;
top: 6px;
margin-right: 16px;
}

这是一个工作示例。

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

您可以尝试以下代码:

<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>

最新更新