2

I am generating an HTML string for a table using Apex then passing that into a lightning web component using the @wire decorator. In my HTML file, I am using:

<lightning-formatted-rich-text value={chart.data}></lightning-formatted-rich-text>

to unescape the HTML characters. However, styles from the LWC's .css file are not being applied.

For example, if I simply hard code in the LWC .html file:

<table class="myclass" ... </table>

the CSS is correctly applied. But if I pass this code in from Apex the styling for myclass will not be applied.

1
  • 2
    I believe that injecting the HTML into a lightning-formatted-rich-text component will make that markup a part of that component and it will not be accessible by CSS in the parent. You may have to use style instead.
    – nbrown
    Jun 10, 2020 at 18:59

2 Answers 2

0

Welcome to the community. I think nbrown is right, I also couldn't reach the content of lightning-formatted-rich-text using the CSS file.

Looking at the documentation it appears that Salesforce are using inline-styling in their examples as well richtext = "<h2 style=\"text-align: center\">Default <s>Value</s></h2>";. So that can be one option for you.

Another option could be the use of lwc:dom=manual.

Add this directive to a native HTML element to call appendChild() on the element from the owner’s JavaScript class and preserve styling.

Check this playground to see an example. I believe that approach can work for your scenario. However you should be wary that there are certain limitations when using lwc:dom=manual on a native HTML element.

1
  • Thank you for the help!
    – Max
    Jun 12, 2020 at 21:50
0

You can easily resolve this issue of styling by using the directive lwc:dom="manual" on your element. No need to use the richtext component.

We had a similar issue in the past where css classes was not being applied. Here is a sample code:

<div lwc:dom="manual">{{generatedHTML}}</div>

Here's the definition of lwc:dom="manual" as per Salesforce documentation:

Add this directive to a native HTML element to call appendChild() on the element from the owner’s JavaScript class and preserve styling.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .