自定义打开/关闭图标
隐藏现有的基于 CSS 的箭头并用我们自己的自定义图标替换它们。使用选择列表打开状态来确定显示哪个图标
- 隐藏现有箭头。
:host mat-select ::ng-deep .mat-select-arrow {
border: 0;
}
::ng-deep .mat-form-field.mat-focused.mat-primary .mat-select-arrow
{
border: 0;
}
- 跟踪选择打开状态
<mat-select [(ngModel)]="selectedFood" openedChange)="handleOpenChange()">
panelIsOpen: boolean = false;
handleOpenChange() {
this.panelIsOpen = !this.panelIsOpen;
}
- 显示适当的图标
<mat-icon class="my-icon" *ngIf="panelIsOpen">arrow_circle_down</mat-icon>
<mat-icon class="my-icon" *ngIf="!panelIsOpen">arrow_circle_up</mat-icon>
移动清除按钮
为清除按钮和向上/向下按钮创建一个包装器,以便我们可以使用 CSS 来排列它们
- 将按钮包装在 div 中并使用 class my-suffix 设置样式
<div matSuffix class="my-suffix">
<button matSuffix mat-icon-button aria-label="Clear"
(click)="onClick($event)">
<mat-icon>cancel</mat-icon>
</button>
<mat-icon class="my-icon" *ngIf="panelIsOpen">arrow_circle_down</mat-icon>
<mat-icon class="my-icon" *ngIf="!panelIsOpen">arrow_circle_up</mat-icon>
</div>
- 样式化包装器
.my-suffix {
display: flex;
align-items:center;
}
- 控制清除按钮的可见性。注意 ngIf 没有被使用,因为这将在 DOM 中插入/删除按钮,并导致选择在插入/删除时改变大小。
<button matSuffix [style.visibility]="!selectedFood? 'hidden': 'visible'" mat-icon-button aria-label="Clear"
(click)="onClick($event)">
<mat-icon>cancel</mat-icon>
</button>
工作示例here
如果链接将来过期,完整的代码
import { Component } from "@angular/core";
interface Food {
value: string;
viewValue: string;
}
@Component({
selector: "select-overview-example",
templateUrl: "select-overview-example.html",
styles: [
`
:host mat-select ::ng-deep .mat-select-arrow {
border: 0;
}
::ng-deep .mat-form-field.mat-focused.mat-primary .mat-select-arrow {
border: 0;
}
.my-suffix {
display: flex;
align-items:center;
}
`
]
})
export class SelectOverviewExample {
selectedFood: string;
panelIsOpen: boolean = false;
handleOpen() {
this.panelIsOpen = !this.panelIsOpen;
}
foods: Food[] = [
{ value: "steak-0", viewValue: "item 1" },
{ value: "pizza-1", viewValue: "item 2" },
{ value: "tacos-21", viewValue: "item 3" },
{ value: "tacos-22", viewValue: "item 4" },
{ value: "tacos-23", viewValue: "item 5" },
{ value: "tacos-24", viewValue: "item 6" },
{ value: "tacos-25", viewValue: "item 7" }
];
onClick(event: any) {
this.selectedFood = "";
event.stopPropagation();
}
}
<mat-form-field [floatLabel]="'never'">
<mat-label>Search</mat-label>
<mat-select [(ngModel)]="selectedFood" disableOptionCentering panelClass="dva-mat-select-container"
(openedChange)="handleOpen()">
<mat-option *ngFor="let item of foods" [value]="item.value">
{{ item.viewValue }}
</mat-option>
</mat-select>
<div matSuffix class="my-suffix">
<button matSuffix [style.visibility]="!selectedFood? 'hidden': 'visible'" mat-icon-button aria-label="Clear"
(click)="onClick($event)">
<mat-icon>cancel</mat-icon>
</button>
<mat-icon class="my-icon" *ngIf="panelIsOpen">arrow_circle_down</mat-icon>
<mat-icon class="my-icon" *ngIf="!panelIsOpen">arrow_circle_up</mat-icon>
</div>
</mat-form-field>