Convert Html to show like a String

1.6k Views Asked by At

I am inserting data from QUILL text editor, which is stored in HTML format. When I access the data to show somewhere it is showing same as HTML, I need that to show as normal text.

<div class="card p-3 mb-3" [innerHTML]="mcq.question ">

JSON from DB:

0:
answer: "&lt;p>mcq-1 A&lt;/p>"
question: "&lt;p>mcq-1\tQ&lt;/p>"

my output is like this which has to be converted to normal text

2

There are 2 best solutions below

2
Mahdi Zarei On

This function will do the work:

function decodeSpecialEntitiesHtml(html) {
  const str = document.createElement("textarea");
  str.innerHTML = html;
  return str.value;
}

var html = '&lt;p>mcq-1 A&lt;/p>'

document.getElementById('withoutFunction').innerText = html;
document.getElementById('withFunction').innerText = decodeSpecialEntitiesHtml(html);
<label>without func:</label><div id="withoutFunction"></div>
<br>
<label>with func:</label><div id="withFunction"></div>
<br>

So you can use it like:

<div class="card p-3 mb-3" [innerText]="decodeSpecialEntitiesHtml(mcq.question)">

Because you want HTML to behave like text. So basically it is a text that is look like a html. so bind it with innerText.


TypeScript

The typescript-friendly function will be:

public decodeSpecialEntitiesHtml(html) {
  const str = document.createElement("textarea");
  str.innerHTML = html;
  return str.value;
}

and use it in template like:

<div [innerText]="decodeSpecialEntitiesHtml(serverHtmlResponse)"></div>
1
childersd On

The first thing that comes to mind is that the HTML is simply not valid. Are you sure that it's formatted correctly?

Another possibility: have you tried marking the HTML as safe using The DomSanitizer? Depending on the type of tags that are used, Angular may stop it from rendering to prevent XSS attacks.

Note: only do this when you are 100% sure that the HTML is safe.