Angular Material - How to add a tooltip to a disabled button

跟風遠走 提交于 2019-12-06 18:18:19

问题


I've noticed that the directive matTooltip doesn't work on a disabled button. How can I achieve it?

Example:

<button mat-raised-button [disabled]="true" matTooltip="You cannot delete that">
  <mat-icon>delete</mat-icon>
</button>

For an enabled button it works perfectly:

<button mat-raised-button [disabled]="false" matTooltip="You cannot delete that">
  <mat-icon>delete</mat-icon>
</button>

回答1:


This doesn't work because it is triggered by mouseenter event which doesn't get fired by most browsers for disabled elements. A workaround is to add matTooltip to a parent element:

<div matTooltip="You cannot delete that" [matTooltipDisabled]="!isButtonDisabled()">
    <button mat-raised-button [disabled]="isButtonDisabled()">
        <mat-icon>delete</mat-icon>
    </button>
</div>

The example above assumes that there is a method for determining if the button should be enabled or not. By using matTooltipDisabled the tooltip will be shown only if the button is disabled.

References:

  • https://github.com/angular/material2/issues/5040
  • https://github.com/angular/material2/issues/7953



回答2:


I had a similar issue while displaying tooltip on a disabled icon button. The given solution was not practical for me, because adding an additional div on top of the button, messed up the layout of the button relative to the other buttons in the tool bar.

A simpler solution for me was to add the tooltip inside the icon inside the button. Something like this:

<button mat-raised-button [disabled]="true">
    <mat-icon matTooltip="You cannot delete that">delete</mat-icon>
</button>

Since the icon is not disabled, it works.




回答3:


Yes, the simplest solution is like above. But for my case I needed more flexibility.

   <button  [disabled]="form.invalid">
      <span [matTooltip]="form.invalid ? 'some text' : ''">button text</span>
    </button>


来源:https://stackoverflow.com/questions/48277909/angular-material-how-to-add-a-tooltip-to-a-disabled-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!