How to Render String with HTML Tags in Angular 4+

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Get an html code from string and display it in angular

First of all, we need a DomSanitizer instance in the class, so we declare it in the constructor:
constructor(private sanitizer: DomSanitizer)

And this is the code for converting the string to a SafeHtml object, that we can import to our html code:

const parser = new DOMParser();
const document = parser.parseFromString(mensaje.cuerpo, 'text/html');
modalRef.componentInstance.body = this.sanitizer.bypassSecurityTrustHtml(document.body.outerHTML);

The last thing missing is to tell out HTML that this code is not malicious and it's safe to display it with the [innerHTML] tag:

<div [innerHTML]="body"></div>

Working!

how to display HTML with angular function?

You need to use [innerHTML] property in your html file

<div class="row justify-content-center">
<div class="col-12 col-lg-6">
<h2>Questions</h2>
<div [innerHTML]="displayQCM()"></div>
<div [innerHTML]="displayQuestion()"></div>
<div [innerHTML]="displayTrueOrFalse()"></div>
</div>
</div>

Output

Angular 5 How to insert a string as a HTML element

You can create custom angular pipe as follows:

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

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

in HTML component,

 <div [innerHTML]="comments | safeHtml"></div>


Related Topics



Leave a reply



Submit