I am looking for a way to compute the remaining width of a div after adding inner spans dynamically
GetWidth() {
let txt = divElement;
console.log(event.target.closest('span').scrollWidth);
}
HTML
<div
style="border: 1px solid gray; height: auto; width: 230px"
>
<span
*ngFor="let item of pgFilters[i].value; let i = index"
>
{{ item }}
</span>
<input (keyup.enter)="add($event, i)" />
</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..
CodePudding user response:
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);
}
CodePudding user response:
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 style="border: 1px solid gray; height: auto; width: 230px">
<div id="filter-elements">
<span *ngFor="let item of pgFilters[i].value; let i = index"
>
{{ item }}
</span>
</div>
<input (keyup.enter)="add($event, i)" />
</div>