Hello friends, In this post you will learn, how to render dynamic html and css in lwc. In many requirement, you have to create dynamic html using javascript/apex and rendered it in html file for the user visibility. so for this type of scenario you can use this example, so let's get started,

Dynamic html and css rendering in lightning web component

In lightning component we used aura:unescapedHtml element to render the dynamic html but in lwc we used lightning-formatted-rich-text element to do the same thing. so let's understand this using an example.

DynamicHtml.html

 <template>
<lightning-card title="Dynamic HTML and CSS Rendering" icon-name="action:announcement">
<lightning-formatted-rich-text value={tableHtml}></lightning-formatted-rich-text>
</lightning-card>
</template>
DynamicHtml.js
 import { LightningElement } from 'lwc';
export default class DynamicHtml extends LightningElement {
tableHtml;
connectedCallback() {
this.tableHtml = "<table style=\"margin-left:20px;\" border=\"1\"><tr><td style=\"color:green;font-weight:bold;\">Dynamic</td><td style=\"color:red;font-weight:bold;\">HTML</td></tr></table>";
}
}
DynamicHtml.js-meta.xml
 <?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>

Output:

  

Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.