Angular Material - How to add a tooltip to a disab

2020-08-09 04:48发布

问题:

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>


回答4:

You can use title attribute it will display in necessary cases

<button mat-raised-button [disabled]="true" title = "Some text">
  <mat-icon>delete</mat-icon>
</button>

you can do property binding with ternary operators



回答5:

I find a solution!

Put the tooltip into the button content like this:

<button type="submit" [disabled]="disableEdit()" class="btn btn-primary btn-sm"
        [routerLink]="['/entity', entity.id, 'edit']">
    <div matTooltip="{{ 'entity.placeholders.cantEdit' | translate }}"
         [matTooltipDisabled]="disableEdit()">
        <fa-icon [icon]="'pencil-alt'"></fa-icon>
        <span class="d-none d-md-inline">{{ 'entity.action.edit' | translate }}</span>
    </div>
</button>


回答6:

Try this:

<div [matTooltip]="isDisabled ? 'You cannot delete that' : ''">
    <button mat-raised-button [disabled]="isDisabled">
      <mat-icon>delete</mat-icon>
    </button>
    <div>