Show Tooltip When Text Ellipsis In Angular

Show Tooltip When Text Ellipsis In Angular

In this article, we will learn how to Show Tooltip When Text Ellipsis in an angular application.

So, let's start with the implementation

First, we need to create a new angular application using the following command in the terminal.

ng new text-ellipsis-angular

Now, we need to create Ellipsis directive using the following command

ng generate directive Ellipsis

Now, add the following code under the ellipsis.directive.ts file.

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);
    }
}

Now, we need to import EllipsisDirective into the app.module.ts file using the following code.

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 { }

Now, Add the following code under the app.component.html file.

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

Now, add the following code under the app.component.scss file.

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

Now, run the application using the ng serve command into the terminal and on the browser screen we are able to show tooltip when we hover on ellipsis text.

Conclusion

In this article, we learned how to how to Show Tooltip When Text Ellipsis in an angular application using the directive.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post