【发布时间】:2020-01-08 13:36:55
【问题描述】:
我有 2 个 mat-card 组件,每个组件包含一个 mat-select。我跟踪mat-card 当前所在的鼠标。因此我使用 2 个事件:
- mouseenter - 当鼠标在垫卡上时
- mouseleave - 当它离开卡片时
这些事件会触发将更新所选垫卡的方法。
HTML:
<div fxLayout="column" fxLayoutGap="50px">
<mat-card (mouseenter)="select('0')" (mouseleave)="unselectCards()">
<h4>Basic mat-select</h4>
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select>
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</mat-card>
<mat-card (mouseenter)="select('1')" (mouseleave)="unselectCards()">
<h4>Basic mat-select</h4>
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select>
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</mat-card>
<span>Selected: {{ selectedCard }}</span>
</div>
TS:
import {Component} from '@angular/core';
export interface Food {
value: string;
viewValue: string;
}
/**
* @title Basic select
*/
@Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
selectedCard = '1';
foods: Food[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
select(card: string) {
this.selectedCard = card;
}
unselectCards() {
this.selectedCard = '';
}
}
这里的关键问题是当我打开mat-select 来选择一个选项时。这将触发 无意的mouseleave 事件。你知道如何防止mouseleave事件的触发吗?
简短的事实:
-
selectedCard保存鼠标当前卡片位置的值 - (mouseenter) 选择卡片
- (mouseleave) 将值设置为空字符串
-
mat-select触发我不想要的 (mouseleave) 事件。它应该保持与以前相同的值。我该如何解决这个问题。
到目前为止,谢谢。
【问题讨论】:
-
更新了演示链接
-
你到底想在这里做什么?
-
我想在操作某些表单元素的同时保持在选定的卡片上而不失去焦点,但目前我只是触摸 mat-select 元素时失去焦点