-
Hello there, I would like to use global styles with a lit component. I tried removing the shadow DOM, but it worked partially. What's the correct way of doing this? In stencil, the end result of: @Component({
tag: 'my-component',
shadow: false,
})
export class MyComponent {
@Prop() count: number = 0;
private _onClick() {
this.count += 1;
}
render() {
return <button class="btn btn-primary" onClick={() => this._onClick()}>
<slot />
{this.count}
</button>;
}
} being used like this: <my-component>
<span> Count in</span>
</my-component> However, with lit, this: @customElement('my-element')
export class MyElement extends LitElement {
@property({ type: Number })
count = 0
protected createRenderRoot(): Element | ShadowRoot {
return this.attachShadow({slotAssignment: 'named', mode:"open", delegatesFocus: false});
}
render() {
return html`
<button class="btn btn-primary" @click=${() => this._onClick()}>
Count: ${this.count}
<slot></slot>
</button>
`
}
private _onClick() {
// console.log("the click was processed")
this.count++
}
} being used like: <my-element>
This is child content
</my-element> and when I tried removing the shadow DOM with: protected createRenderRoot(): Element | ShadowRoot {
return this;
} Any ideas? I'm making a CSS theme, we cannot use |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I have found that this makes the style work: protected createRenderRoot(): Element | ShadowRoot {
let root = this.attachShadow({mode: 'open'})
let link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', 'theme.css');
root.appendChild(link);
return root;
} |
Beta Was this translation helpful? Give feedback.
-
If you use mor than one stylesheet or if you use webpack, which may rename the stylesheets: I created a base class that essentially attaches all the stylesheets from the head. This way, even security headers are cloned as well. export class BaseElement extends LitElement {
protected createRenderRoot(): Element | ShadowRoot {
let root = this.attachShadow({ mode: 'open' });
const links = document.head.getElementsByTagName('link');
for (let i = 0; i < links.length; i++) {
const link = links.item(i);
if (!link || link.rel !== 'stylesheet') {
continue;
}
root.appendChild(link.cloneNode(true));
}
return root;
}
} |
Beta Was this translation helpful? Give feedback.
I have found that this makes the style work: