Here's a bit of a cleaner solution I've found for this use-case. Instead of CSS, I used the slice angular pipe, where the two values mark the start and end of the sliced characters.
Angular Ellipsis with Slice and *ngIf
- Slice pipe isolates first 20 characters
- A
span follows with a manually written "..." string
- The ellipsis span is conditional on how many characters are showing using
item.name.length and having it either be greater or equal to the number of characters allowed from the slice
<a *ngFor="let item of items">
{{ item.name | slice: 0 : 20 }}<span *ngIf="item.name.length >=20">...</span>
</a>
Show Tooltip Conditionally
I also wanted this to display a tooltip. But I didn't want any other anchors to have a tooltip unless the ellipsis was present (since the tooltip would show the entire name)
Template
- With
mouseover, uses a ternary operator that triggers an onHover method IF it has equal or more characters than previous identified
- The
onHover method takes in both the $event and the name (string) of the item
- Tooltip has styling required to appear at mouse coords (
absolute) but binds component variables to [style.top] and [style.left] so it appears where mouse event fires
- The
(mouseout) ensures the tooltip is gone when no longer hovering over the element
<a
*ngFor="let item of items"
(mouseover)="(item.name.length >= 20) ? onHover($event, item.name) : '' "
(mouseout)="showsTooltip ? (showsTooltip = !showsTooltip) : '' ">
{{ item.name | slice: 0 : 20 }}<span *ngIf="item.name.length >=20">...</span>
</a>
<!-- some other code -->
<div
*ngIf="showsTooltip"
[style.top]="tooltipTopY"
[style.left]="tooltipLeftX"
class="tooltip"
>
{{ tooltipText }}
</div>
Component
- Catches the coordinates from the event object and binds them accordingly
export class SomeComponent implements OnInit {
showsTooltip = false;
tooltipText = '';
tooltipTopY!: any;
tooltipLeftX!: any;
// ... other code
onHover(e: any, cardName: string): void {
this.tooltipText = cardName;
if (e) {
this.showsTooltip = true;
this.tooltipTopY = e.clientY + 'px';
this.tooltipLeftX = e.clientX + 'px';
}
}
}
Hope this helps! Grateful for thorough answers that've helped me here; and I find this solution has been pretty clutch for me so far - so just hoping to share where I can!