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

标签 angular angular-directive

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

    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"
            />

最佳答案

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

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

然后使用引用将结果绑定(bind)到 [matTooltipDisabled] 有点像:

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

快速示例:https://stackblitz.com/edit/angular-mjz2n7

关于angular - 无法通过自定义指令以编程方式启用和禁用 matTooltip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166008/

相关文章:

javascript - 如何创建可扩展的 Angular 应用程序结构?

angular - 如何在等待响应时取消 http.post()?

javascript - 指令的依赖

angular - Angular 2 内部组件

angular - 如果 nginx 正在运行(dockerized),则无法构建 Angular dist

javascript - 如何模拟具有 require 字段的 Angular Directive(指令)

angularjs - 如何使用 jqlite 以 Angular 获取元素的 attr 数据?

javascript - Angular 1.5 组件 - 从指令转换后未呈现模板

http - Angular 2 http delete 不发出网络请求

angular - 如何以 Angular 访问 ElementRef.nativeElement 的嵌套元素