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.
The correct solution for this problem:
I have two matmenus in my toolbar each one is a separate component and triggers a separate matmenu.
See images below:
Here is my notifications component(component 1 in the image above)
In my editor view :
In my notifications.component.html file :
I don’t think it is possible to have two in one component but I hope this helps.
This issue is related to the element referencing in angular, so you cannot directly use the mat-menu in a single component.
The trick to do is to create a component that implements the mat-menu:
Eg,
mat-menu.component.html:
mat-menu.component.ts
Now you can use this component multiple times in any component.
Eg,
app.component.html
It will work.
I had the same issue and I solved it by using the
read
metadata property of @ViewChild decoratormainmenu.component.html
mainmenu.component.ts
The trick is to use the template reference
menuBtn1
ormenuBtn2
and specify through theread
property what you want to get that is theMatMenuTrigger
directiveNOTE: I saw that the question refers to angular and angular-material 5. I tested it with angular 8 but it should be the same