Dynamic Lightning Web Component in Salesforce
Enable dynamic component for LWC
To get started with dynamic component for lwc, we have to enable it for the salesforce org.
Setup -> Search for Session Settings
enable Use Lightning Web Security for Lightning web components and Aura components
This will enable dynamic components in the org.
Add dynamic component in component configuration file
Api version should be greater than 55.0 to use dynamic component in lwc.
<capabilities>
<capability>lightning__dynamicComponent</capability>
</capabilities>
Add dynamic child component to parent lwc
<template>
<lwc:component lwc:is={componentConstructor}></lwc:component>
</template>
lwc:component
acts as the placeholder for the DOM (Document Object Model) that renders the specified dynamic component. lwc:is
directive must be used with lwc:component
. lwc:is
directive provides an imported constructor at runtime to the lwc:component
and lwc:is
accepts the expression that resolves to a LightningElement
constructor at runtime. If constructor is true then it renders all the child elements other wise they are not rendered.
If constructor value is defined but not a LightningElement
constructor then it throws an error.
componentConstructor;
connectedCallback() {
import("c/dynamicComponent")
.then(({ default: ctor }) => (this.componentConstructor = ctor))
.catch((err) => console.log("Error importing dynamic component"));
}
The import call basically returns a promise which resolve to a LightningElement
constructor. The element is then rendered instead of lwc:component
.
Similar to a regular component, the dynamic component is instantiated and attached to the DOM. If the dynamic component's constructor changes, the existing element is removed from the DOM.