无法通过自定义指令以编程方式启用和禁用matTooltip

问题描述 投票:1回答:1

这是正在使用的自定义指令,

    constructor(
      private el: ElementRef,
      private renderer: Renderer
    ) { }

    @HostListener('mouseover') onHover() {
    const offWidth = this.el.nativeElement.offsetWidth;
    const scrollWidth = this.el.nativeElement.scrollWidth;
    if(offWidth < scrollWidth) {
        this.renderer.setElementAttribute(this.el.nativeElement, 'matTooltipDisabled', false);
        console.log("enable tooltip");
    } else {
        this.renderer.setElementAttribute(this.el.nativeElement, 'matTooltipDisabled', true);
        console.log("disable tooltip");
    }
}

这不起作用。垫工具提示始终处于启用状态。该属性已正确更新为true和false,但始终显示工具提示。

           <input
                appMyCustomDirective
                class="testclass"
                name="testval"
                id="testid"
                [(ngModel)]="testval"
                type="text"
                autocomplete="off"
                [matTooltip] = "testval"
                matTooltipClass = "tooltip"
                matTooltipPosition = "above"
            />
angular angular-directive
1个回答
2
投票

创建实现条件的指令并导出相同的引用:

@Directive({
  selector: '[isOutOfBound]',
  exportAs: 'outOfBound'
})
export class IsOutOfBoundDirective {
  constructor() { }
  @Input('isOutOfBound') outOfBound = false;
  @HostListener('mouseenter') onEnter() {
    this.outOfBound = !this.outOfBound;
  }
}

然后使用引用将结果绑定到[matTooltipDisabled],如下所示:

<button mat-raised-button
    matTooltip="Info about the action"
    [isOutOfBound]
    #c="outOfBound"
    [matTooltipDisabled]="c.outOfBound"
    >

快速样本:https://stackblitz.com/edit/angular-mjz2n7

© www.soinside.com 2019 - 2024. All rights reserved.