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,以显示实际的设置和问题。
提前谢谢!
而不是将值设置为
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> |
现在
1 2 3 4 5 | .selection-icon { position: relative; top: 6px; margin-right: 16px; } |
这是一个可行的示例。
注意:为了设置此选定对象的值,您可以传递原始数组本身中的一个对象(例如
您可以尝试以下代码:
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> |