3

I am creating an angular component that displays a highlighted HTML code and the result of it's execution. The displayed HTML code lives inside a pre html element, as for the preview of the result, it's hard-coded :

<pre class="prettyprint lang-html">

&lt;button type="button" class="btn btn-danger">Danger&lt;/button> <br> &lt;p> Hello World! &lt;/p>

</pre>
<button type="button" class="btn btn-danger">Danger</button>
<p> Hello Wolrd </p>

The result of using this component is as following

Now what I want to do is to pass this HTML code as an input to this component. I tried to pass the code as a string using the following string :

&lt;button type=\"button\" class=\"btn btn-danger\">Danger&lt;/button> <br> &lt;p> Hello World! &lt;/p>

The input what displayed as a string and was not executed displayed as an HTML code : image

How can i use this input string to 1. display it as html code and 2. execute this code to preview the result ? Otherwise, what's the type that i should use for the input ?

Thanks for you're help.

1 Answer 1

5

Solution for this is to create a custom pipe that bypass security trust html:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({name: 'sanitizeHtml'})
export class SanitizeHtmlPipe implements PipeTransform {
  constructor(private _sanitizer:DomSanitizer) {
  }
  transform(v:string):SafeHtml {
    return this._sanitizer.bypassSecurityTrustHtml(v);
  }
}

Declare it in your module and use it where you want to display the HTML string :

<div [innerHTML]=" yourHTMLstring | sanitizeHtml "> </div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.