4

What I want to do

I want to be able to work out how much of a string is shown before it is truncated.

Why I want to do it

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.

Basic example

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

What I have tried

  • Using element.innerHTML and element.innerText to read the displayed string. both show the full string, not the displayed truncated string.
Jamie Clark
  • 252
  • 1
  • 13
  • 3
    If the panel is fixed width you can work off of the number of characters after which the ellipsis happens, but that might get iffy with different font sizes. If it's not fixed width I'd recommend not handling the ellipsis in CSS but rather in the constructor of the `panel.component.ts` and adding 2 new variables - shortTitle and itemsHidden and working with that. – Dropout Sep 07 '21 at 09:21
  • 1
    What you basically want to do is to get the count of the hidden content if the css of the panel is ```overflow: hidden``` – Shivam Puri Sep 07 '21 at 10:26

1 Answers1

1

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;

}

Shyam Joshi
  • 830
  • 7
  • 18