prady
prady

Reputation: 426

Trigger mat-menu in child component from parent component

I am using angular 6 with angular-material. Opening matMenu on right click to use it as contextmenu. My current code looks like this.

<span #contextMenuTrigger [matMenuTriggerFor]="contextMenu"></span>
<button (contextmenu)="openContextMenu($event)" mat-button >Open Context Menu</button>
<mat-menu #contextMenu="matMenu">
    <ng-container *ngFor="let item of config.items">
      <button mat-menu-item [matMenuTriggerFor]="submenu" (click)="actionSelected(item.label)">{{ item.label }}</button>
      <mat-menu #submenu="matMenu">
         <button *ngFor="let subItem of item.submenu" mat-menu-item (click)="actionSelected(subItem.label)">{{ subItem.label }}</button>
      </mat-menu>
    </ng-container>
  </mat-menu>

I am opening menu programmatically in my typescript component class like this.

@ViewChild('contextMenuTrigger', {read: MatMenuTrigger}) contextMenuTrigger:MatMenuTrigger;

  ngOnInit() {

  }

  openContextMenu(e) {
    e.preventDefault();
    this.contextMenuTrigger.openMenu();
  }

This all is working fine.

Now for real scenerio what i want is , i want this contextmenu to be opened from parent component. So i moved this part to app.component.html

<span #contextMenuTrigger [matMenuTriggerFor]="contextMenu"></span>
    <button (contextmenu)="openContextMenu($event)" mat-button >Open Context Menu</button>

I used EventEmitter to pass instance of MatMenu i.e. contextMenu to parent.

But my question is how do i assign matMenuTriggerFor property in parent component. if i remove it from span its giving error.

AppComponent.html:1 ERROR Error: mat-menu-trigger: must pass in an mat-menu instance.

also not working when i do document.getElementById("span id").matMenuTriggerFor = my menu instance.

Please suggest any way. let me know if any further information is needed.

Upvotes: 2

Views: 5813

Answers (1)

lordchancellor
lordchancellor

Reputation: 4107

Just to make sure I'm reading your question correctly, I'm assuming that your method openContextMenu() is in the child component? If so, you could use a ViewChild in the parent component in order to access that method from the parent. So something like this:

Parent Code:

import { Component, ViewChild } from '@angular/core';

import { ChildComponent } from '/path/to/child.component';

@Component({})
export class ParentComponent {

  @ViewChild(ChildComponent) childComponent: ChildComponent;

  onClick(event) {
    childComponent.openContextMenu(event);
  }

}

Upvotes: 4

Related Questions