How to activate tooltip when ellipsis is activated using a directive in angular 5?

时光怂恿深爱的人放手 提交于 2019-11-30 21:11:08

问题


I have the following template with a "dotdotdot" css class which add ellipsis on overflow correctly.

<div class="dotdotdot">{{data.trip.name}}</div>

What I'm trying to do here is to implement a directive which add a tooltip when the ellipsis is activated only.

Here is the current code from the directive:

import { Directive, OnInit, ElementRef } from '@angular/core';

declare var $: any;

@Directive({
  selector: '.dotdotdot'
})
export class DotdotdotDirective implements OnInit {

  private el: HTMLElement;
  constructor(elRef: ElementRef) {
    this.el = elRef.nativeElement;
}

ngOnInit() {           
         if (this.isEllipsisActive(this.el)) {   
            // TODO add title attribute to the div with value from text         
            $(this.el).tooltip();     
         }         
}

isEllipsisActive(e) {
     return (e.offsetWidth < e.scrollWidth);
}

}

I have two problems in the code above:

  1. isEllipsisActive is not working, I need the way to identified the ellipsis.
  2. I need to know how to add title or [title] attribute dynamically from $(this.el). The value is the text from the div.

Thanks!


回答1:


You can create this directive:

import { AfterViewInit, Directive, ElementRef, EventEmitter, Output } from 

'@angular/core';

@Directive({
  selector: '[isEllipsisActive]'
})
export class IsEllipsisActiveDirective implements AfterViewInit {

  constructor(private elementRef: ElementRef) {}

  ngAfterViewInit(): void {
    setTimeout(() => {
      const element = this.elementRef.nativeElement;
      if(element.offsetWidth < element.scrollWidth){
        element.title = element.innerHTML;
      }
    }, 500);
  }
}

take a look on this https://stackblitz.com/edit/angular-qjmg7m?file=src%2Fapp%2Fis-ellipsis-active.directive.ts




回答2:


Great answer by ofir - Here's a modified version that will work if text changes after initialization.

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[isEllipsisActive]'
})

export class isEllipsisActiveDirective {

  constructor(private elementRef: ElementRef) {}

  @HostListener('mouseenter')
  onMouseEnter(): void {
    setTimeout(() => {
      const element = this.elementRef.nativeElement;
      if (element.offsetWidth < element.scrollWidth) {
        element.title = element.textContent;
      }
      else if (element.title) element.removeAttribute('title'); 
    }, 500);
  }
}


来源:https://stackoverflow.com/questions/52480394/how-to-activate-tooltip-when-ellipsis-is-activated-using-a-directive-in-angular

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