Angular

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:

Jignesh Patel

Jignesh Patel is a Senior Full Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET MVC, AngularJS, Angular, Nodejs, Web API, EPPlus, SQL, Entity Framework, JavaScript, Azure Web Jobs, Microsoft Graph API, etc.

View Comments

  • 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...

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago