Created
June 26, 2017 19:38
-
-
Save boneskull/27f8003eeb605900a907ae8d8fd42c10 to your computer and use it in GitHub Desktop.
Angular directive to simulate "text-overflow: ellipsis" on an SVG text node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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}`; | |
} | |
} | |
} | |
} |
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);
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
Anyway solved it myself, but your directive is very helpful, thanks a bunch...