I want to be able to work out how much of a string is shown before it is truncated.
I have a list of items. You can select any amount of items from this list. I have a panel element that shows a comma separated string of the selected selected item names. If the string is too long, it should be truncated and display a +{number} value of any additional selected items hidden by the truncate.
https://stackblitz.com/edit/angular-ivy-cbyemy
The stackblitz above shows a basic example of the use case.
Currently panel title:
an item, another item, som... +6
Desired result:
an item, another item, som... +3
Borrowed an answer from here and modified it a bit as per requirement.
Your forked stackblitz, updated working demo here.
You can get the count of visible characters from this function -
countVisibleCharacters(element): number {
var text = element.firstChild.nodeValue;
var count = 0;
element.removeChild(element.firstChild);
for (var i = 0; i < text.length; i++) {
var newNode = document.createElement('span');
newNode.appendChild(document.createTextNode(text.charAt(i)));
element.appendChild(newNode);
if (newNode.offsetLeft < element.offsetWidth) {
count++;
}
}
return count;
}
Then you can get the suffix this way -
getTitleSuffix(): void {
let element = document.getElementById('title');
let count = this.countVisibleCharacters(element);
let substr = element.textContent;
substr = substr.substring(count - 1);
this.titleSuffix = substr.split(',').length;
}