Last active
August 15, 2023 06:09
-
-
Save thomasloven/5f965bd26e5f69876890886c09dd9ba8 to your computer and use it in GitHub Desktop.
How to use ha elements when using ScopedRegistry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { LitElement, html } from "lit"; | |
import { customElement, property } from "lit/decorators.js"; | |
import { ScopedRegistryHost } from "@lit-labs/scoped-registry-mixin"; | |
@customElement("customelement-test") | |
class CustomElementTest extends ScopedRegistryHost(LitElement) { | |
@property() hass; | |
static elementDefinitions = { | |
"ha-card": customElements.get("ha-card"), // This works because ha-card is ALWAYS loaded before custom cards (for now) | |
}; | |
setConfig(config) {} | |
firstUpdated() { | |
// Elements can only be added to the local customElement registry after | |
// createRenderRoot has run(which ScopedRegistryRoot handles). | |
// It's definitely run before first render, so firstUpdated can be a good | |
// place to start loading elements. | |
this.loadEntityPicker(); | |
} | |
async loadEntityPicker() { | |
// Get the local customElement registry | |
const registry = (this.shadowRoot as any)?.customElements; | |
if (!registry) return; | |
// Check if the element we want is already defined in the local scope | |
if (registry.get("ha-entity-picker")) return; | |
// Load in ha-entity-picker | |
// This part will differ for every element you want | |
const ch = await (window as any).loadCardHelpers(); | |
const c = await ch.createCardElement({ type: "entities", entities: [] }); | |
await c.constructor.getConfigElement(); | |
// Since ha-elements are not using scopedRegistry we can get a reference to | |
// the newly loaded element from the global customElement registry... | |
const haEntityPicker = window.customElements.get("ha-entity-picker"); | |
// ... and use that reference to register the same element in the local registry | |
registry.define("ha-entity-picker", haEntityPicker); | |
} | |
render() { | |
return html` | |
<ha-card> | |
Hello! <ha-entity-picker .hass=${this.hass}></ha-entity-picker> | |
</ha-card> | |
`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@thomasloven this no longer appears to work with 2022.11bx. The call to window.customElements.get("ha-entity-picker"); returns undefined.