I am quite new to Angular 5 and have just started learning it.
Recently, I have been trying to create a menu bar with multiple menus for my app using Angular 5 Material.
The menu will be triggered/opened during mouse enter and closed when the mouse leaves the menu.
My problem is that everytime the mouse mouse hovers to the first menu it loads the menu items of the 2nd menu.
Here is a screenshot of the problem:
Here are my codes:
mainmenu.component.html:
<div>
<button mat-button [matMenuTriggerFor]="menu1"
(mouseenter)="openMyMenu()">Trigger1</button>
<mat-menu #menu1="matMenu" overlapTrigger="false">
<span (mouseleave)="closeMyMenu()">
<button mat-menu-item>Item 1</button>
<button mat-menu-item>Item 2</button>
</span>
</mat-menu>
</div>
<div>
<button mat-button [matMenuTriggerFor]="menu2"
(mouseenter)="openMyMenu()">Trigger2</button>
<mat-menu #menu2="matMenu" overlapTrigger="false">
<span (mouseleave)="closeMyMenu()">
<button mat-menu-item>Item 3</button>
<button mat-menu-item>Item 4</button>
</span>
</mat-menu>
</div>
mainmenu.component.ts:
import { Component, OnInit, ViewChild } from '@angular/core';
import {MatMenuTrigger} from '@angular/material'
@Component({
selector: 'app-mainmenu',
templateUrl: './mainmenu.component.html',
styleUrls: ['./mainmenu.component.css']
})
export class MainmenuComponent implements OnInit {
@ViewChild(MatMenuTrigger) matMenuTrigger: MatMenuTrigger;
constructor() { }
ngOnInit() {
}
openMyMenu() {
this.matMenuTrigger.openMenu();
}
closeMyMenu() {
this.matMenuTrigger.closeMenu();
}
}
I also tried this: @ViewChild('menu1') matMenuTrigger: MatMenuTrigger;
but I am getting errors.
Your opinions and advices are very much appreciated!
Thanks,
Artanis Zeratul
References:
I had the same issue.
Create two separate components, each will then contain its own mat-menu and will not affect the other.
<!-- component1 -->
<div>
<button mat-button [matMenuTriggerFor]="menu1"
(mouseenter)="openMyMenu()">Trigger1</button>
<mat-menu #menu1="matMenu" overlapTrigger="false">
<span (mouseleave)="closeMyMenu()">
<button mat-menu-item>Item 1</button>
<button mat-menu-item>Item 2</button>
</span>
</mat-menu>
</div>
<!-- component2 -->
<div>
<button mat-button [matMenuTriggerFor]="menu2"
(mouseenter)="openMyMenu()">Trigger2</button>
<mat-menu #menu2="matMenu" overlapTrigger="false">
<span (mouseleave)="closeMyMenu()">
<button mat-menu-item>Item 3</button>
<button mat-menu-item>Item 4</button>
</span>
</mat-menu>
</div>