Search code examples
angularangular-materialangular7angular-material2viewchild

Close Mat-menu when user scrolls the window


Problem: Should't visible mat-menu When Window Scrolls on top of nav menu,

Cause: it rises because of high z-index in .cdk-overlay-container

I have trailed following

file.ts

@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; 
@HostListener('window:scroll', [])
scrollHandler() {
if (this.trigger) {
this.trigger.closeMenu();
 }
 }

But which is worked only for first mat-menu out of 6, rest not closing on scroll !!!!!

Angular Cli Version


Solution

  •  @ViewChildren(MatMenuTrigger) trigger: QueryList<MatMenuTrigger>;
     @HostListener('window:scroll', [])
     scrollHandler() {
         for (let index = 0; index < this.trigger.toArray().length; index++) {
       this.trigger.toArray()[index].closeMenu();
     }
    

    this will access all the mat-menus inside the component and the loop will iterate over each index and closes the menu opened.