2

I am trying to dynamically populate HTML elements in my LWC. However it is showing as text, escaping the HTML characters.

I tried using <lightning-formatted-rich-text> but that is also not doing the trick for me.

Below is a sample of the code I've tried implementing.

HTML

<template>
    <div class="wrapper"
        <template for:each={tableColumnContentWrapper} for:item='contentColumn'>
            <div class="row" key={contentColumn.fieldName}>
                <div class="column">
                    <lightning-formatted-rich-text value={contentColumn.stateHtml}></lightning-formatted-rich-text>
                </div>
            </div>
        </template>
</template>

JavaScript

import { LightningElement, track } from 'lwc';

export default class MyClass extends LightningElement {
    @track tableColumnContentWrapper = [
        {
            fieldName: 'state',
            stateHtml: '<input type="text" placeholder="Your state" class="data-input"/>'
        }
    ];
}

This is what I see in the inspector:

preview

Any ideas would be appreciated.

EDIT

I do understand that this is not rich-text and as such it's not inserting an <input /> element as I tested with <h1></h1> and that seems to be working alright.

I can modify the innerHTML but I wanted to try and see if there's a cleaner way of doing this first.

0

As per the documentation:

If you set unsupported tags via JavaScript, those tags are removed and the text content is preserved. The supported HTML tags are: a, abbr, acronym, address, b, br, big, blockquote, caption, cite, code, col, colgroup, del, div, dl, dd, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, ins, kbd, li, ol, mark, p, param, pre, q, s, samp, small, span, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, var, strike.

Lightning Web Component Formatted Rich Tex

The input tag is not included in the list. Plus you will need to replace the double quotes by single quotes in the html you are trying to render, or escape the double quotes by adding a backslash ( \" ) to every instance.

And in your template code, you are missing the closing tag for the wrapper div ;)

| improve this answer | |
0

To dynamically populate HTML in lightning web component you have to do below things:

Define the element in LWC as :

 <div class="elementHoldingHTMLContent" lwc:dom="manual">
 </div>

Populate the HTML content from javascript as :

this.template.querySelector('.elementHoldingHTMLContent').innerHTML = contentColumn.stateHtml;

Please note lwc:dom="manual" is important, that way you should be able to update innerHTML.

| improve this answer | |

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.