Rya*_*es8 1 angular-material angular
我正在 Angular 7 中工作,我的要求之一是使用 mat-icons 创建一个 mat-select。我遇到的问题是我可以显示图标,也可以显示选项标签,但不能同时显示两者。我需要做的是能够链接该值,但是当我尝试时出现错误。
垫子选择设置如下-
<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>
Run Code Online (Sandbox Code Playgroud)
我已将选定的图标和标签放置在 mat-select-trigger 中,并将值放置在 food.value 中。
选择的界面是
export interface Food {
value: string;
viewValue: string;
icon: any;
}
Run Code Online (Sandbox Code Playgroud)
并且选择选项设置为
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';
Run Code Online (Sandbox Code Playgroud)
如果我将值更改为 food.icon,我可以让选择选项图标显示为选择。如果我将 value 更改为 food.viewValue 我会看到选项的标签出现。
当用户做出选择时,如何才能同时获得两者?
我已经设置了一个Stackblitz来展示实际的设置和问题。
先感谢您!
不要将值设置为icon或viewValue,而是将其设置为整个对象。这样,所选值将包含整个对象中的数据。然后,您可以简单地使用所选对象中的属性来获得您想要的内容。
<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>
Run Code Online (Sandbox Code Playgroud)
现在 和 都icon将viewValue显示在选择触发器中。您所需要做的就是修复图标的 css,因为它不会与viewValue.
.selection-icon {
position: relative;
top: 6px;
margin-right: 16px;
}
Run Code Online (Sandbox Code Playgroud)
这是一个工作示例。
注意:为了设置此选定对象的值,您可以从原始数组本身传递一个对象(例如public selected2 = foods[0]),或者您可以使用compareWith以便select能够跟踪值,因为我们的选项value是一个对象。这与trackBy中的类似ngFor。基本上,要么传递原始数组的引用,以便可以select跟踪它,要么使用compareWith告诉select跟踪基于每个对象中的某些唯一值的数组中的对象。
| 归档时间: |
|
| 查看次数: |
7272 次 |
| 最近记录: |