2

We have a requirement of having some template in which we can inject the components dynamically with dependency injection at runtime using configuration. We are exploring the LWC for this since it's based on ES6. Since ES6 support OOPS, we are thinking of having reusable modules that helps in creating the DOM elements dynamically at runtime. For example,

export default class BaseElement{
    constructor(name, label){
       this.name = name;
       this.label = label;
    }
}

Button class extends the BaseElement

export default class Button extends BaseElement{
    constructor(name, label){
        super(name, label);            
    }
}

Template HTML for button element

<template>
   <lightning-button name={name} label={label}><lightning-button>
<template>

App Container

export default App extends LightningElement{
   constructor(baseElement){
       this.element = baseElement;
   }

   appendToElement(el){
      //Append the element template HTML content to body
   }

   getElementHTML(){
      return this.element.template.content; //Do we have any method to get the template markup?
   }      
}

We want to follow these patterns to dynamically inject elements in runtime using Dependency injection pattern to reuse the LWC components.

  1. Is this possible with LWC or should we use 3rd party libraries like jquery to manipulate the DOM?
  2. Even using jquery imported as a module, we still need to get the template markup, how would we get that?

Thanks in advance..

1

You can't. There has been some random chatter on Twitter about allowing dynamic construction, the same as we'd use $A.createComponents, but support for this has not been formally announced as a current or upcoming feature (so, don't count on it being available anytime soon, if ever). If you use jQuery, AngularJS, or any other DOM-manipulation script/framework, it must be contained inside a <div lwc:dom="manual"> element, and the script will only be allowed to manipulate the DOM elements contained within. This will also be limited to only plain HTML elements, not LWC or Aura components. If you need this sort of capability, you'll need to use Aura Components for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.