Angular:如何在一个HTML中打开两个Mat菜单?

时间:2018-12-06 05:53:45

标签: angular angular-material

enter image description here

在这里,我在一个组件的HTML中有两个Matmenus。当打开第二个菜单时(当我右键单击该div时,第二个菜单就打开了),但是它打开了第一个菜单,那么如何以不同的角度单击以不同的方式打开一个组件HTML中的两个菜单?

HTML

(this is first menu)
<mat-icon style="cursor: pointer;" [matMenuTriggerFor]="menu">more_vert   
  <mat-menu #menu="matMenu"> 
    <button mat-menu-item (click)="addNewItem()">New Folder</button>
    <button mat-menu-item (click)="uploadFiles()">Upload Files</button>
  </mat-menu> 
</mat-icon>

(This is second menu)

<mat-card *ngFor="let imagespayload of uploadedImagesObj"(click)="activeFolder=imagespayload"
   (contextmenu)="onContextMenu($event, imagespayload)">

   <div style="position: fixed"
     [style.left]="contextMenuPosition.x"
     [style.top]="contextMenuPosition.y"
     [matMenuTriggerFor]="contextMenu"
     [matMenuTriggerData]="{item: imagespayload}">
   </div>

  <mat-menu #contextMenu="matMenu">
    <ng-template matMenuContent let-item="item">
      <button mat-menu-item>Action 1</button>
      <button mat-menu-item>Action 2</button>
    </ng-template>
  </mat-menu>

TS

  import { Component, OnInit, Input,ViewChild } from '@angular/core';
  import { MatMenuTrigger } from '@angular/material';

  @ViewChild(MatMenuTrigger) contextMenu: MatMenuTrigger;
  contextMenuPosition = { x: '0px', y: '0px' };

 onContextMenu(event: MouseEvent, imagespayload) {
   event.preventDefault();
   this.contextMenuPosition.x = event.clientX + 'px';
   this.contextMenuPosition.y = event.clientY + 'px';
   this.contextMenu.menuData = { imagespayload};
   this.contextMenu.openMenu();
}

1 个答案:

答案 0 :(得分:1)

第一个菜单打开,而不是第二个菜单打开,因为@ViewChild()绑定到与给定选择器匹配的第一个指令,在本例中为第一个菜单的matMenuTrigger。要将其绑定到第二个菜单触发器,请在带有触发器的元素上使用模板引用变量:

<div #trigger="matMenuTrigger"
    style="position: fixed"
    [style.left]="contextMenuPosition.x"
    [style.top]="contextMenuPosition.y"
    [matMenuTriggerFor]="contextMenu"
    [matMenuTriggerData]="{item: imagespayload}">
</div>

然后,在您的.ts中:

@ViewChild('trigger') trigger: MatMenuTrigger;

this.trigger.openMenu();

有关参考,请参见Angular ViewChild documentationMatMenuTrigger APIthis post,了解如何将模板引用变量与指令一起使用。