Skip to content

Instantly share code, notes, and snippets.

@boneskull
Created June 26, 2017 19:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save boneskull/27f8003eeb605900a907ae8d8fd42c10 to your computer and use it in GitHub Desktop.
Save boneskull/27f8003eeb605900a907ae8d8fd42c10 to your computer and use it in GitHub Desktop.
Angular directive to simulate "text-overflow: ellipsis" on an SVG text node
/**
* @see https://stackoverflow.com/questions/15975440/add-ellipses-to-overflowing-text-in-svg
* @example
* <!-- truncate at 200px -->
* <svg><svg:text ellipsis [text]="text to truncate" [width]="200"></svg:text></svg>
*/
import {
Directive,
ElementRef,
Input,
OnInit
} from '@angular/core';
const ELLIPSIS = '\u2026';
@Directive({selector: 'svg text[ellipsis]'})
export class SVGEllipsisDirective implements OnInit {
@Input() text: string;
@Input() width: number;
constructor (private _el: ElementRef) {
}
ngOnInit (): void {
this._textEllipsis(this._el.nativeElement);
}
private _textEllipsis (el: SVGTextContentElement) {
let text = this.text;
const width = this.width;
if (typeof el.getSubStringLength !== 'undefined') {
el.textContent = text;
let len = text.length;
if (el.getSubStringLength(0, len) > width) {
while (el.getSubStringLength(0, len--) > width) {
}
el.textContent = text.slice(0, len) + ELLIPSIS;
}
} else if (typeof el.getComputedTextLength !== 'undefined') {
while (el.getComputedTextLength() > width) {
text = text.slice(0, -1);
el.textContent = `${text}${ELLIPSIS}`;
}
} else {
// the last fallback
while (el.getBBox().width > width) {
text = text.slice(0, -1);
// we need to update the textContent to update the boundary width
el.textContent = `${text}${ELLIPSIS}`;
}
}
}
}
@kernelex
Copy link

to show tooltip add this code in the end of _textEllipsis() function :

    const titleEl = document.createElementNS('http://www.w3.org/2000/svg', 'title');
    titleEl.textContent = this.text;
    el.appendChild(titleEl);

@boneskull
Copy link
Author

No idea, haven’t played with Angular for years, sorry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment