Show Tooltip When Text Ellipsis In Angular

In this article, we will learn how to show a tooltip when text is ellipsis.

The following example demonstrates how to show a Tooltip when text is overflow with an ellipsis.

First, we need to add a directive using the following command:

ng generate directive Ellipsis

Open the ellipsis.directive.ts file and add the code to it.

import {
    AfterViewInit,
    Directive,
    ElementRef
} from "@angular/core";

@Directive({
    selector: "[isEllipsis]"
})
export class EllipsisDirective implements AfterViewInit {
    constructor(private elementRef: ElementRef) { }

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

Open the ellipsis.directive.ts file and add the code to it.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EllipsisDirective } from './elipsis.Directive';

@NgModule({
  declarations: [
    AppComponent,
    EllipsisDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  exports: [EllipsisDirective],
  bootstrap: [AppComponent]
})
export class AppModule { }

Open the ellipsis.directive.ts file and add the code to it.

<div isEllipsis class="ellipsis">
    how to activate tooltip when text are ellipsis using a directive in angular.
</div>

Open the app.component.scss file and add the code to it.

.ellipsis{
  width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Output:

3 Comments

  1. Luqman Hakim Omar Ali

    Hi, how about when you try to activate the tooltip for ellipsis in table?

    0
    0
    Reply
  2. YuraM

    What you gonna do when your element will be inline like or , in this case your scrollWidth will be always 0, besides you’ll never see ellipsis on inline elements without another css property as { display: block }, scrollWidth would equals to 0, kinda fragile solution…

    0
    0
    Reply
    1. YuraM

      i meant span or italic tags above

      0
      0
      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories