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:

Submit a Comment

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

Footer Logo

Subscribe

Select Categories