Show Truncated tooltip in <@angular/>
In UI development we come across such things like not to show tooltip/title when the text is completely showing.
We can solve this problem by assigning classes to each text content and that would be so much hectic.
In angular we use Directive for solving some common issue throughout the application. Here we are going to work on a angular directive that will solve our showing tooltip on satisfying any condition.
We require..
Angular app setup
Node dev version developed
Bootstrap / any library (I am using angular bootstrap here).
What is Angular Directive ?
In angular a directive is like special instruction you give to html element to make them do something cool dynamically. In could be something they look, adding new feature or making them appear or disappear based on condition.
This is an attribute directive as i am using the directive as an attribute in a html tag. e.g<p directive>Lorem ipsum...</p>
Let's create and set up the app.
npm i -g @angular/cli //for installing angular app globally
ng new your-app-name //creating an angular app
ng add @ng-bootstrap/ng-bootstrap //adding angular bootstrap to the project.
Now that we have created our app and set it up, we are going to create a directive that decides the functionality of our app.
ng g d directive-name // for creating directive in our app.
My directive is like this..
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';
import { Directive, ElementRef, Renderer2, OnInit } from '@angular/core';
@Directive({
selector: '[appTruncatedTextTooltip]'
})
export class TruncatedTextTooltipDirective implements OnInit {
constructor(private el: ElementRef, private ngbTooltip:NgbTooltip) {}
ngOnInit(): void {
setTimeout(() => {
const isTextTruncated = this.isTextTruncated(this.el.nativeElement);
if (isTextTruncated) {
this.ngbTooltip.open();
this.ngbTooltip.ngbTooltip = this.el.nativeElement.innerText;
}
});
}
private isTextTruncated(element: HTMLElement): boolean {
return element.offsetWidth < element.scrollWidth;
}
}
lets understand this..
I have explained the method in the picture. how it checks element.offsetWidth and element.scrollWidth. Then it returns a boolean value.
Our HTML would look like this.
<li class="col-md-4 text-truncate my-2" appTruncatedTextTooltip ngbTooltip>Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid amet quasi doloremque odit totam sequi itaque sapiente corrupti blanditiis nihil impedit alias modi, consectetur facere a laudantium at ad fugiat.</li>
Here the ngbTooltip is for reference of the inner text. It send the content of the li tag to the directive as a reference.
Now you can see the desired results.
For you reference i have created an app based on this you can check here Github.
You can check the functional project here https://texttruncate.web.app/.
_Thank you.
Please share your feedback.