1

I have a string response containing escaped HTML that I am trying to render inside a div using innerHTML. The table is not getting rendered. Instead i'm seeing the output as unescaped html with the table tags : <table width=583px><tr><td>Sunshine</td><td>Unicorns</td></tr></table>. Is there a work around for this?

In my test.component.ts,

public testStringWithEscape = '&lt;table width=583px&gt;&lt;tr&gt;&lt;td&gt;Sunshine&lt;/td&gt;&lt;td&gt;Unicorns&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;';

in test.component.html,

<div [innerHtml]="testStringWithEscape"></div>

P.S: I know that we have solution for this in javascript/angular JS. But I'm specifically trying to understand if there is a way in Angular4/6/8.

Siena
  • 778
  • 10
  • 23
  • You can replace the string to html tags [See this answer](https://stackoverflow.com/a/15604206/11719787) – Sameer Jan 23 '20 at 11:06
  • so, the api response is escaped html, and we need to render the response in application. – Siena Jan 23 '20 at 11:08
  • There are several ways to do this [See this answer](https://stackoverflow.com/a/1912522/11719787), Just research before posting any question :) – Sameer Jan 23 '20 at 11:13
  • I am looking for angular 6/8 specific solutions. Thanks anyways! – Siena Jan 23 '20 at 11:15

1 Answers1

0

You can use this function:

function htmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

see here for usage

ivan
  • 51
  • 5