Reputation: 2990
I'm working on a native WebComponent that represents a simple table, the number of row and columns are coming via attributes. The width of columns if fixed.
In case that I have 20 columns and column width = 150px, I need to create only as many columns as I can fit in the parent container without creating a y-overflow.
here is how I create the table
...
this._root = this.attachShadow({mode: "open"});
...
_createTable() {
const parentWidth = this.getRootNode(); // how to get the width of parent container
console.log(222, parentWidth)
this._cells = [];
this._table = document.createElement('table');
for (let row = 0; row < this._rows; row++) {
const tr = document.createElement('tr');
this._table.appendChild(tr);
this._cells.push([]);
let totalWidth = 0;
for (let col = 0; col < this._cols; col++) {
// can we create a new cell/column
if (totalWidth + this._columnWidth > parentWidth)
break;
totalWidth += this._columnWidth;
const td = document.createElement('td');
td.innerText = `cell[${row}${col}]`;
tr.appendChild(td);
this._cells[row].push(td);
}
}
this._root.appendChild(this._table);
}
but I could not find a way how from my web-component
to get the parent width and attach to its resize event.
Because the web-component is inside a shadow-dom, I cannot really access the parent, maybe I'm wrong here, but parentNode
always returns null.
Ideas?
Upvotes: 1
Views: 562
Reputation: 36
ShadowRoot is a DocumentFragment, so they will always have parentNode
set to null
, but they do have a host
property pointing to the element they are attached to.
Upvotes: 2