Reputation: 71
What I am trying to accomplish
I am trying to dynamically create a 2-level cascading menu with angular and material components.
Now, I would like to trigger the second level menu when hovering on a first level element.
...
// Level 1 Menu
<button class="cq-but" md-menu-item *ngIf="item.type === 'sub'"
[mdMenuTriggerFor]= ... // <- how do I reference mdMenu here??
item.name
</button>
// Level 2 Menu
<md-menu class="cq-popup" *ngIf="item.type === 'sub'" #subMenu="mdMenu" id=item.name>
<button md-menu-item *ngFor="let childitem of item.children">
childitem.name
</button>
</md-menu>
</md-list-item>
What I need help with
The dyanmically generated md-menu needs to be triggered via a [mdMenuTriggerFor]in the buttons on the first level.
As I've noted in the code snippet above, my question is... how do I bind to the dynamically generated md-menu component in my mdMenuTriggerFor directive?
**What I have tried ** - I tried to get a reference to the subMenu using ViewChildren i.e.
// @ViewChildren('subMenu') public subMenu:QueryList<MdMenu>;
hoping to programmatically trigger the menu without having to provide the mdMenuTriggerFor directive in the template. However that does not work because according to https://material.angular.io/components/component/menu the mdMenuTriggerFor directive is necessary to attach the menu to a trigger element in the DOM
Open to other approaches. Thanks!
Upvotes: 2
Views: 1371
Reputation: 9357
Here is one way to do it: you can use <ng-container>
and it will just create a private scope for your template variable (https://stackblitz.com/edit/repeating-menu-approach-2):
<table class="table table-striped">
<ng-container *ngFor="let el of [1,2,3,4,5]">
<tr>
<td>Text line of menu {{el}}</td>
<td style="width: 5%">
<button mat-icon-button [matMenuTriggerFor]="menu">
<mat-icon>more_vert</md-icon>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item (click)="clickHandler('Item 1 of Menu ' + el)">Menu {{el}}:Item 1</button>
<button mat-menu-item (click)="clickHandler('Item 2 of Menu ' + el)">Menu {{el}}:Item 2</button>
</mat-menu>
</td>
</tr>
</ng-container>
</table>
Interestingly, each #menu
template variable above will be unique, successfully isolated from the others #menu
template variables created by the *ngFor
loop.
Upvotes: 1