pro*_*ogx 0 javascript typescript angular-material angular
仅当用户选择一个选项时,我才尝试在 Angular 材料中的下拉列表(选择组件)的右侧添加一个清晰的图标。如果用户单击“清除”图标,我想删除该值并重置该字段。到目前为止,我有下拉菜单并努力正确显示图标。有人能指出我正确的方向吗?提前致谢。
这是我的代码:
<mat-form-field appearance="fill">
<mat-label>Select a food</mat-label>
<mat-select>
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
<mat-select-trigger>
<button>
<mat-icon>clear</mat-icon>
</button>
</mat-select-trigger>
</mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
这是现场演示
您需要在 mat-select 上添加 ngModel 以进行双向绑定,以将选定的值添加到其中。还要添加按钮作为 mat-select 的后缀。
<mat-select [(ngModel)]="selectedFood">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{ food.viewValue }}
</mat-option>
</mat-select>
<button mat-button matSuffix *ngIf="selectedFood" mat-icon-button (click)="onClick($event)">
<mat-icon>close</mat-icon>
</button>
Run Code Online (Sandbox Code Playgroud)
在您的组件方面,您需要添加以下功能来清除选定的食物值。
onClick(event: any) {
this.selectedFood = "";
event.stopPropagation();
}
Run Code Online (Sandbox Code Playgroud)
event.stopPropagation() 将停止在单击清理按钮时打开选择下拉列表。
这是您的工作解决方案:
https://stackblitz.com/edit/angular-c7hgum-94nqyq
| 归档时间: |
|
| 查看次数: |
5540 次 |
| 最近记录: |