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 [innerHTML]="mcq.question ">
JSON from DB:
0:
answer: "<p>mcq-1 A</p>"
question: "<p>mcq-1\tQ</p>"
CodePudding user response:
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.
CodePudding user response:
This function will do the work:
function decodeSpecialEntitiesHtml(html) {
const str = document.createElement("textarea");
str.innerHTML = html;
return str.value;
}
var html = '<p>mcq-1 A</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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
So you can use it like:
<div [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>