Angular Material MatToolTip 仅在元素被截断时显示

Angular Material MatToolTip show up only when the element is truncated

(编辑:求助各位,我快死了,这个问题没有完全解决,请参考评论)

我想让 matTooltip 仅在标签实际溢出时显示。 喜欢:when text is overflown,如果不是,则没有工具提示。

这是我尝试使用 matTooltipDisabled:

时损坏的代码

HTML(有些代码我用“...”删除了,因为我认为它们不是问题所必需的。基本上在 HTML 中,有些标签不会显示unless you click on the dropdown,这也是工具提示的一个问题):

<div *ngFor="...; let i = index">
            <div class="panel-container-label">
              <div *ngIf="i < 5" fxLayout="row" fxLayoutAlign="space-between center">
                <div>
                  <span matTooltip="..." [matTooltipPosition]="'after'" [matTooltipDisabled]="!ifOverflow(toolTip)" #toolTip>
                    <mat-checkbox class="search-facet-checkboxes" ...>
                      ...
                    </mat-checkbox>
                  </span>
                </div>
              </div>
              <div *ngIf="i >= 5 &&..." fxLayout="row" fxLayoutAlign="space-between center">
                <div class="container-name-oflw">
                  <span matTooltip="..." [matTooltipPosition]="'after'" [matTooltipDisabled]="!ifOverflow(toolTip)" #toolTip>
                    <mat-checkbox class="search-facet-checkboxes" ...>
                      ...
                    </mat-checkbox>
                  </span>
                </div>
              </div>
            </div>
          </div>

CSS:

.search-facet-checkboxes .mat-checkbox-layout .mat-checkbox-label {
  font-weight: normal !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}

div.panel-container-label {
  background-color: #ffffff;
  color: #487980;
  padding: 0 10px;
  clear: both;
  overflow: hidden;
  .container-name-oflw {
    width: 170px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

TS:

ifOverflow(e){
    console.log(e.scrollWidth + " and " + e.clientWidth)
    return e.scrollWidth > e.clientWidth;
  }

然后控制台为 scrollWidthClientWidth 都打印 0,我不知道为什么。

我也用 ViewChild 和本地参考 #toolTip 尝试了一些东西,但也没有成功,我在控制台上收到一个错误,说 Cannot read property 'native-element' of undefined.

我真的不想像这样使用没有 Angular Material 的指令:https://medium.com/@anup.bangale/showing-tooltip-only-when-text-overflow-ellipsis-active-angular8-bd5e9d7667a9,因为这将涉及创建一个新文件,我需要使用 Angular Material。

我几乎浏览了与此问题相关的所有 Stack Overflow 帖子。请大家帮忙,谢谢!

看来你的想法是对的。但我认为您需要使用 div 而不是 span,或者在 CSS 中将显示更改为 blockinline-block。因为 inline 元素的宽度为 0。我之前已经实现了同样的想法,所以我整理了一个简单的例子以防它有帮助:

https://stackblitz.com/edit/angular-material-tooltip-overflow

关于 inline 元素宽度的信息: