Reputation: 5181
I have 2 mat-card
components which contains a mat-select
each. I track the mouse on which mat-card
it currently is. Therefore I use 2 events:
Those events triggers methods that will update the selected mat-card.
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 = '';
}
}
The key issue here is when I open the mat-select
to select an option. This will trigger the mouseleave
event which is not intended. Do you know how to prevent the triggering of the mouseleave
event?
Short facts:
selectedCard
holds the value of the current card location of the mousemat-select
triggers the (mouseleave) event what I don't want. It should stay on the same value as before. How can I solve this.Thank you so far.
Demo: https://stackblitz.com/edit/angular-48t5yk
Upvotes: 0
Views: 1734
Reputation: 11
I just had the same problem. Solved it by checking the target of the MouseEvent.
component.html
<div (mouseleave)="onMouseLeave($event)">your component</div>
component.ts
onMouseLeave(event: MouseEvent): void {
if ((event.relatedTarget as HTMLInputElement).className !== 'mat-option-text') {
// your action on leave
}
}
Upvotes: 1
Reputation: 71961
I suppose you can check if the mat-select
is open or not like this and update the selection when the mat-select
toggles:
<mat-card (mouseenter)="select('1')" (mouseleave)="!matSelect.panelOpen && unselectCards()">
<h4>Basic mat-select</h4>
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select #matSelect="matSelect" (openedChange)="$event ? select('1') : unselectCards()">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</mat-card>
Upvotes: 1