2.4 | How to create nested component instances dynamically within elementary Cubbles components

As you may know, elementary components have an associated logic. This logic is a script where you can interact with the component. Additionally, you can add nested component instances within your elementary. To aim that you should:

  1. Create the desired component tag using the document.createElement method
  2. Append the component to the DOM using the Polymer API
  3. Call Polymer.dom.flush() if you then need to interrogate to DOM (e.g. you need offsetHeight, getComptedStyle, etc.)
  4. Add the dependency of the desired component to the rootDependencies in the app where you will use your elementary

The code below presents this process for adding a new cubx-textarea as  nested component of a component called my-elementary:

<my-elementary> logic
 ...
 // 1. Create the desired component tag using the document.createElement method
 var elem = document.createElement('cubx-textarea');
 
 // 2. Append the component to the DOM using the Polymer API
 Polymer.dom(this.root).appendChild(elem);
 
 // 3. Call Polymer.dom.flush()  (if needed)
 Polymer.dom.flush()
 ...
App
<head>
	...
	<script src="https://cubbles.world/sandbox/cubx.core.rte@2.2.3/webcomponents-lite/webcomponents-lite.js"></script>
	<script>
		  // 4. You should add the dependency of the desired component to the rootDependencies
    	  window.cubx = {
        	"CRCInit": {
          	"rootDependencies": [
        	       {
    	              "webpackageId": "com.incowia.basic-html-components@1.2",
	                  "artifactId": "cubx-textarea"
              		}
           		]
	        }
    	  }
	</script>
	<script src="https://cubbles.world/sandbox/cubx.core.rte@2.2.3/crc-loader/js/main.js" data-crcinit-loadcif="true"></script>
</head>


<body>
	...

	<my-elementary cubx-webpackage-id="this"></my-elementary>
	
	...
</body>

You may also be interested in defining inits and connections for the component before appending it to the DOM. Then, you should checkt the 2.4 | The Cubbles Tag API and the 2.4 | The Cubbles Javascript API.

Use document.createElement

Although you may want to append the component using the innerHTML property of a container, we recommend you to use the document.createElement() method, so that everything works properly.