in my HTML code, I have a <p>
tag with a maximum width set using the maxWidthProductId input in my component. If the text within this
tag exceeds the maximum width, ellipsis (…) will be applied. However, I’m facing difficulty detecting whether text-overflow: ellipsis is active because I don’t have any scrollbars in my element, so the method (element.clientWidth < element.scrollWidth) doesn’t work for me. Here is my HTML and CSS code:
<p class="productId__text" #test [style.max-width]="maxWidthProductId" >{{ productId }}</p>
<span *ngIf="this.isTextOverflow ===true" class="tooltip" #tooltip>{{ productId }}<br /></span>
.productId__text{
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
max-width:300px;
margin: 0;
}
Is there another solution ?
2
Answers
See that, as "test" is the template refrence, in the .html is the own HTMLelement.
If you are not using scrollbars and want to detect whether text-overflow: ellipsis is active, you can use a combination of JavaScript and DOM manipulation to check the overflow condition. One approach is to compare the clientWidth with the scrollWidth. However, since you mentioned that this method doesn’t work for you, you can consider an alternative approach using the
getComputedStyle
method.Here’s how you can achieve it:
First, add a reference variable to your
<p>
tag in the template:In your component, use
ViewChild
to get a reference to the<p>
element and check the computed style to determine if text-overflow: ellipsis is applied:This way, the
checkTextOverflow
method will be called after the view has been initialized, and it will determine whether text-overflow: ellipsis is active by comparing the scrollWidth and clientWidth or checking the computed style. If there is text overflow, you can display the tooltip accordingly.