简体   繁体   English

Angular Material - 仅当条件为真时才在鼠标悬停时显示 Mat-Menu

[英]Angular Material - displaying Mat-Menu on mouse-over only when condition is true

quick question.快速提问。 I want to trigger Mat-menu on mouse over div element with header of my component, but only when some specific condition is set to true.我想在鼠标悬停在带有组件标题的 div 元素上触发Mat-menu ,但仅当某些特定条件设置为 true 时。

I have something like this:我有这样的事情:

<div class="card-header"
     [matMenuTriggerFor]="comp.RejectionDetails ? rejectionDetails : null" 
     #trigger="matMenuTrigger" (mouseenter)="trigger.openMenu()" 
     (mouseleave)="trigger.closeMenu()">
  <mat-menu #rejectionDetails [class]="'mat-menu-component'"
            [hasBackdrop]="false">
      <ng-template matMenuContent>
           <div>TEST</div>
      </ng-template>
  </mat-menu>

It's seems to work as expected but in console it's throwing error:它似乎按预期工作但在控制台中它抛出错误:

UniversalDynamicComponent.html:10 ERROR Error: matMenuTriggerFor: must pass in an mat-menu instance. UniversalDynamicComponent.html:10 错误错误:matMenuTriggerFor:必须传入 mat-menu 实例。

 Example: <mat-menu #menu="matMenu"></mat-menu> <button [matMenuTriggerFor]="menu"></button>

I understand that is because of passing null value to directive (when the conidition is false).我知道这是因为将空值传递给指令(当条件为假时)。 But I can't figure out other solution for this problem.但我想不出解决这个问题的其他方法。 Maybe someone can help?也许有人可以帮忙? Thanks!谢谢!

Try to set your condition not on [matMenuTriggerFor], but on (mouseenter) event like that:尝试不在 [matMenuTriggerFor] 上设置条件,而是在 (mouseenter) 事件上设置这样的条件:

 [matMenuTriggerFor]="rejectionDetails" 
 (mouseenter) = "comp.RejectionDetails ? trigger.openMenu() : null"  

After spending 2-3 hours on this, the most easiest workaround I found for this problem is,花了 2-3 小时后,我发现这个问题最简单的解决方法是,

  1. Define 2 mat-menu one for your normal behavior and other menu to show nothing.定义 2 个垫子菜单,一个用于您的正常行为,另一个菜单不显示任何内容。 (reason to do this is because "matMenuTriggerFor" cannot be false or null it needs to have a mat-menu object) (这样做的原因是因为“matMenuTriggerFor”不能为 false 或 null 它需要有一个 mat-menu 对象)

     <mat-menu #sub_menu="matMenu"> <button>menu-button 1</button> <button>menu-button 2</button> </mat-menu> <mat-menu #fake_menu="matMenu" class="fake-menu"></mat-menu>
  2. now put a condition on your "matMenuTriggerFor" like this:现在像这样在你的“matMenuTriggerFor”上设置一个条件:

     [matMenuTriggerFor]="your-boolean-condition? your-normal-menu: fake-menu"
  3. On CSS just write在 CSS 上只写

     ::ng-deep {.fake-menu { display: none; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM