diff --git a/packages/components/src/components/table/table.tsx b/packages/components/src/components/table/table.tsx index 52730fd025..a01b0252ae 100644 --- a/packages/components/src/components/table/table.tsx +++ b/packages/components/src/components/table/table.tsx @@ -9,7 +9,7 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ -import { Component, Prop, h, Element, Host } from '@stencil/core'; +import { Component, Prop, h, Element, Host, State } from '@stencil/core'; import classNames from 'classnames'; import statusNote from '../../utils/status-note'; @@ -19,6 +19,8 @@ import statusNote from '../../utils/status-note'; shadow: false, }) export class Table { + mutationObserver: MutationObserver; + @Element() hostElement: HTMLElement; /** (optional) Display sort arrows on/off */ @Prop() showSort?: boolean = false; @@ -28,19 +30,36 @@ export class Table { @Prop() striped?: boolean = false; /** (optional) Injected CSS styles */ @Prop() styles?: string; + /** "forceUpdate" hack, set it to trigger and re-render */ + @State() forceUpdate: string; /** object of the slots in use */ slots: { header?: Element; table?: Element } = {}; + addSortIndicator(el) { + el.insertAdjacentHTML( + 'afterbegin', + ` + ` + ); + } + componentWillLoad() { this.hostElement.querySelectorAll('th').forEach((th) => { - th.insertAdjacentHTML( - 'afterbegin', - ` - ` - ); + this.addSortIndicator(th); + }); + } + + componentWillUpdate() { + this.hostElement.querySelectorAll('th').forEach((th) => { + // only cols that are NOT added dynamically have children (the sorting icon), added on componentWillLoad + if (th.children.length === 0) { + // this may not be needed + th.classList.add('dynamically-added'); + this.addSortIndicator(th); + } }); } @@ -52,6 +71,13 @@ export class Table { el.showStatus = false; }); } + this.mutationObserver = new MutationObserver(() => { + this.forceUpdate = String(Date.now()); + }); + this.mutationObserver.observe(this.hostElement, { + childList: true, + subtree: true, + }); } componentDidRender() { @@ -66,6 +92,12 @@ export class Table { } } + disconnectedCallback() { + if (this.mutationObserver) { + this.mutationObserver.disconnect(); + } + } + render() { return ( diff --git a/packages/components/src/html/table-dynamic-cols.html b/packages/components/src/html/table-dynamic-cols.html new file mode 100644 index 0000000000..fa019e848c --- /dev/null +++ b/packages/components/src/html/table-dynamic-cols.html @@ -0,0 +1,252 @@ + + + + + + Stencil Component Starter + + + + + + +

Table

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Title + Tags + Stats + + Time + + Euros +
Jane + Other + N/A + Demo + +
+ 9.356 + +
+
00:00:20100.245,10
Jack + Other + N/A + Demo + +
+ 3.356 + +
+
00:00:30100.345,10
John + Other + N/A + Demo + +
+ 6.356 + +
+
00:00:40100.445,10
Total + + 00:00:20100.245,10lol
+
+ + +