'How to compute the remaining free space or width of div?

I am looking for a way to compute the remaining width of a div after adding inner spans dynamically

enter image description here

GetWidth() {
    let txt = divElement;
    console.log(event.target.closest('span').scrollWidth);
  }

HTML

<div
class="wrapper"
style="border: 1px solid gray; height: auto; width: 230px"
>
<span
*ngFor="let item of pgFilters[i].value; let i = index"
class="cont"
>
{{ item }}
</span>
<input (keyup.enter)="add($event, i)" class="inputx" />
</div>

Style

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.inputx {
  flex-grow: 1;
}

TS

add(event: any, index: number): void {
    const value = (event.target.value || '').trim();
    if (value) {
      this.pgFilters[index].value.push(value);
      event.target.value = '';
}

I have added the complete code.. here i am trying to implement chips control on my own..



Solution 1:[1]

This should do the trick:

It gets the rectangular coordinates of the last <span> using yourSpan.getBoundingClientRect().. so the right property of the object returned describes the distance from the left side of the div... So if you know the parent div's width.. you can just subtract that right property value from the div's width.

function GetRemainingWidth(){
  var div = document.getElementById("div1");
  var w = div.offsetWidth - div.children[div.children.length - 1].getBoundingClientRect().right;
  return `${w}px`
}

console.log(GetRemainingWidth());
<div id="div1">
I weas here
  <span>I am Great!</span> <span>Are you?</span>
</div>

For this code to work... Please do the following in your html. Put the <span> elements into a separate wrapper from the input.

<div class="wrapper" style="border: 1px solid gray; height: auto; width: 230px">
  <div class="filter-elements" id="filter-elements">
    <span *ngFor="let item of pgFilters[i].value; let i = index"
        class="cont"
    >
      {{ item }}
    </span>
  </div>
  <input (keyup.enter)="add($event, i)" class="inputx" />
</div>

Solution 2:[2]

You can use parentElement like this

function remaining(){
let txt = divElement;
let parent=txt.parentElement;
let remain=parent.offsetWidth-txt.offsetWidth}

If you may have multi child in this element you can do this

function remaining(){
    let txt = divElement;
    let parent=txt.parentElement;
Let child=parentElement.children;
 let remain=parent.offsetWidth;
child.foreach(element=>{
remain-=element.offsetWidth;
}
conole.log(remain);
   }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2