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.