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
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?
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's innerHTML. The innerHtml attribute is a standard HTML element attribute to which Angular 14 can bind with square brackets i.e [ & ] .
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With