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>
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
Css ''Background-Color" Attribute Not Working on Checkbox Inside ≪Div≫
How to Style Part of an Input Field'S Value
Font Awesome Icon Inside Text Input Element
Custom Bullet Symbol for <Li> Elements in <Ul> That Is a Regular Character, and Not an Image
Full Width Backgrounds on Outlook '07/'10/'13
Best Approach to Real Time Http Streaming to Html5 Video Client
CSS Background-Size: Cover Replacement for Mobile Safari
How to Set Default Value to the Input[Type="Date"]
How to *Really* Justify a Horizontal Menu in Html+Css
Is Type="Text/Css" Necessary in a ≪Link≫ Tag
How to Change Font-Family of Drop Down's List Item
Tooltip with HTML Content Without JavaScript
Hide Horizontal Scrollbar on an Iframe
Flexbox Column-Reverse in Firefox, Edge and Ie
IE6 + IE7 CSS Problem with Overflow: Hidden; - Position: Relative; Combo
Why Does Margin-Top Work With Inline-Block But Not With Inline