Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind raw html in Angular2 [duplicate]

Tags:

angular

I use Angular 2.0.0-beta.0 and I want to create and bind some simple HTML directly. Is is possible and how?

I tried to use

{{myField}} 

but the text in myField will get escaped.

For Angular 1.x i found hits for ng-bind-html, but this seems not be supported in 2.x

thx Frank

like image 449
fbenoit Avatar asked Jan 04 '16 05:01

fbenoit


People also ask

How do I display HTML inside an angular binding?

To add HTML that contains Angular-specific markup (property or value binding, components, directives, pipes, ...) it is required to add the dynamic module and compile components at runtime. This answer provides more details How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

How do I bind HTML in angular 6?

Data Binding is available right from AngularJS, Angular 2,4 and is now available in Angular 6 as well. We use curly braces for data binding - {{}}; this process is called interpolation. We have already seen in our previous examples how we declared the value to the variable title and the same is printed in the browser.

What is inner HTML in angular?

What's innerHTML. The innerHtml attribute is a standard HTML element attribute to which Angular 14 can bind with square brackets i.e [ & ] .

How do I render a string with HTML tag in angular 8?

To render a html string in angular, we can use the innerHTML property by binding a string to it. The innerHTML property sanitizes the html, so that your app is safe from the cross-site scripting attacks(XSS).


1 Answers

Bind to the innerHTML attribute

There is 2 way to achieve:

<div [innerHTML]="myField"></div> <div innerHTML="{{myField}}"></div> 

To mark the passed HTML as trusted so that Angulars DOM sanitizer doesn't strip parts of

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

with a pipe like

@Pipe({name: 'safeHtml'}) export class Safe {   constructor(private sanitizer:DomSanitizer){}    transform(value: any, args?: any): any {     return this.sanitizer.bypassSecurityTrustHtml(value);     // return this.sanitizer.bypassSecurityTrustStyle(style);     // return this.sanitizer.bypassSecurityTrustXxx(style); - see docs   } } 

See also In RC.1 some styles can't be added using binding syntax

like image 154
Günter Zöchbauer Avatar answered Nov 15 '22 13:11

Günter Zöchbauer