Lightning

Displaying HTML tags from a text field in lightning component

There will be occasions when you need to display some HTML tags like images or icons based on some condition and you end up using a formula text field to create a dynamic tag and save it as text field. It can also be a Rich-Text-Area field which will be saved as a HTML tag in backend.

When displaying the same in salesforce record view, it will take care of itself. But then the same need to be displayed as part of a custom component, which can be achieved using <lightning-formatted-rich-text/>

A lightning-formatted-rich-text component is a read-only representation of rich text. Rich text refers to text that’s formatted by HTML tags, such as <b> for bold text or <u> for underlined text. You can pass in rich text to this component using the lightning-input-rich-text component or programmatically in JavaScript. <lightning-formatted-rich-text />  tag has an attribute named value, where you need to pass the value and any HTML tag related data is displayed in actual format as per tags

HTML File

<template>
    <lightning-formatted-rich-text   
        value={a_Dynamic_Field} >
   </lightning-formatted-rich-text> 
</template>

JS File

import { LightningElement } from 'lwc';
export default class Component_Name extends LightningElement {
    a_Dynamic_Field = ''; // Some record formula field with HTML tag or a rich text field
}

Example of field which contains some HTML tag.

<img src="https://na9.salesforce.com/img/samples/flag_red.gif" alt="" style="height:15px; width:15px;" border="0" />

Output:

Resources:

Formatted Rich Text

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s