How to Dynamically Create Lightning Components in JavaScript
This post is about a cool feature of the aura framework that allowing you to create and render components dynamically using some JS parameters.
To do so all you need to do is to place a certain DOM element with aura:id
in the cmp file.
<div aura:id="compDiv"></div>
On your JS controller set the component Name and pass the parameters along with the name of the ElementId :
const compName ='YourComponent'; let compParameters = { "recordId":component.get('v.recordId); }; helper.buildComponent(component, compName, compParameters ,"compDiv");
Then create a helper method like this to inject the component inside of the DOM element
buildComponent: function(component, compName, compParameters ,divId){ let namespace = 'c:'+compName; $A.createComponents([ [namespace,compParameters]], function(components, status, errorMessage){ if (status === "SUCCESS") { var comp = components[0]; var compDiv = component.find(divId); compDiv.set("v.body", comp); } else if (status === "INCOMPLETE") { console.log("No response from server or client is offline.") // Show offline error } else if (status === "ERROR") { console.log("Error: " + errorMessage); // Show error message } } ); },
As of this post there is no standard way to create dynamic components in lightning web component.