Erick Jhorman Romero
Erick Jhorman Romero

Reputation: 154

How to open a mat-menu from another component using a service?

Hi guys i have two components both of them are siblings for that reason i need to use a service but i don't how to send the instance of the [MatMenuTriggerFor] to my another component. Any help?

This is the code from one of my navBar.component where i have the logic to open my menu but from here .

<li class="nav-item">
        <a class="nav-link" id="categorias" [matMenuTriggerFor]="clickHoverMenu" #clickHoverMenuTrigger="matMenuTrigger"
          (mouseover)="openOnMouseOver($event)">
           Categorias 
            </a>
</li>

and this is the code of my slidebar component where i wanna open my menu

<mat-menu #clickHoverMenu='matMenu'>
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

Thanks for your help

Upvotes: 0

Views: 3368

Answers (2)

JWP
JWP

Reputation: 6963

<mat-expansion-panel [expanded]="expanded">

Works for an expansion-panel. Same concept is true for menu. Then read this article for a centralized event service

Upvotes: 0

mwilson
mwilson

Reputation: 12900

You first need to establish the refrence to your MatMenuTrigger. You can accomplish this using @ViewChild. Then, you can emit the closing/opening with an EventEmitter<T>

Example (https://stackblitz.com/edit/angular-u5gkff?file=src%2Fapp%2Fcomp2%2Fcomp2.component.ts)

Service

@Injectable({ providedIn: 'root' })
export class MyserviceService {
  public menuEmitter: EventEmitter<boolean>;
  constructor() {
    this.menuEmitter = new EventEmitter<boolean>();
  }
  open(): void {
    this.menuEmitter.emit(true);
  }
  close(): void {
    this.menuEmitter.emit(false);
  }
}

Then in any component you want to trigger the menu from:

export class Comp1Component implements OnInit {
  private readonly _myService: MyserviceService;
  constructor(myService: MyserviceService) {
    this._myService = myService;

  }

  ngOnInit() {
  }
  open(): void {
    this._myService.open();
  }
}

Actual Component with MatMenu

export class Comp2Component implements OnInit {
  private readonly _myService: MyserviceService;
  @ViewChild('menuTrigger') matMenuTrigger: MatMenuTrigger;
  constructor(myService: MyserviceService) {
    this._myService = myService;
    this._myService.menuEmitter.subscribe(this.toggleMenu.bind(this));
  }

  ngOnInit() {
  }
  toggleMenu(state: boolean): void {
    this.matMenuTrigger.openMenu();
  }
}

<button mat-button [matMenuTriggerFor]="menu" #menuTrigger="matMenuTrigger" >Menu</button>
<mat-menu #menu="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

Upvotes: 4

Related Questions