javascripthtmlangularhtml-encode

Convert &lt;p&gt; to <p> and use to format html


A web service is returning data to my app in this format (unfortunately I have no control over the server output):

&lt;p&gt; This is a paragraph &lt;/p&gt;

When trying to display this data using innerHtml the result is as follows

<p>This is a paragraph</p>

How do I 'pass on' the formatting to the browser so it interprets the paragraph tag and displays it?

Stackoverflow interpreting the <p>:

This is a paragraph


A plunker to demonstrate https://plnkr.co/edit/BbAVrT8F1rJGZnJmov1g?p=preview, code also listed below.

@Component({
  selector: 'my-app',
  template: `
    <div [innerHtml] = "name">
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `&lt;p&gt;This is a paragraph&lt;/p&gt;`
  }
}

I have tried <script>decodeURI({{name}})</script> but that simply returns <".

I have also looked at other stack questions and tried a pipe to bypass the security of the html, which didn't work. Reading the Angular2 docs it sounds like that's not it's purpose. I also tried the style override, it failed as this is not a style, it's pure html:

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value: string) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

Solution

  • You first need to decode those entity references, you can have the browser do this for you like in my code example below. Let's assume that getData() returns an Observable which contains your data

    .
    .
    .
    class SomeClass ... {
      dataBoundProperty: string;
    
      someFunction() {
        this.dataService.getData()
                .subscribe(dataStr => {
                    let dummyElem = document.createElement('DIV');
                    dummyElem.innerHTML = dataStr;
                    document.body.appendChild(dummyElem);
                    this.dataBoundProperty = dummyElem.textContent; // just grap the decoded string which contains the desired HTML tags
                    document.body.removeChild(dummyElem);
                });
      }
    }