Angular HTML binding

后端 未结 21 2696
暖寄归人
暖寄归人 2020-11-21 04:00

I am writing an Angular application and I have an HTML response I want to display.

How do I do that? If I simply use the binding syntax {{myVal}} it en

相关标签:
21条回答
  • 2020-11-21 04:53

    The correct syntax is the following:

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

    Documentation Reference

    0 讨论(0)
  • 2020-11-21 04:53

    Just to post a little addition to all the great answers so far: If you are using [innerHTML] to render Angular components and are bummed about it not working like me, have a look at the ngx-dynamic-hooks library that I wrote to address this very issue.

    With it, you can load components from dynamic strings/html without compromising security. It actually uses Angular's DOMSanitizer just like [innerHTML] does as well, but retains the ability to load components (in a safe manner).

    See it in action in this Stackblitz.

    0 讨论(0)
  • 2020-11-21 04:57

    Please refer to other answers that are more up-to-date.

    This works for me: <div innerHTML = "{{ myVal }}"></div> (Angular2, Alpha 33)

    According to another SO: Inserting HTML from server into DOM with angular2 (general DOM manipulation in Angular2), "inner-html" is equivalent to "ng-bind-html" in Angular 1.X

    0 讨论(0)
  • 2020-11-21 04:58

    We can always pass html content to innerHTML property to render html dynamic content but that dynamic html content can be infected or malicious also. So before passing dynamic content to innerHTML we should always make sure the content is sanitized (using DOMSanitizer) so that we can escaped all malicious content.

    Try below pipe:

    import { Pipe, PipeTransform } from "@angular/core";
    import { DomSanitizer } from "@angular/platform-browser";
    
    @Pipe({name: 'safeHtml'})
    export class SafeHtmlPipe implements PipeTransform {
        constructor(private sanitized: DomSanitizer) {
        }
        transform(value: string) {
            return this.sanitized.bypassSecurityTrustHtml(value);
        }
    }
    
    Usage:
    <div [innerHTML]="content | safeHtml"></div>
    
    0 讨论(0)
  • If you want that in Angular 2 or Angular 4 and also want to keep inline CSS then you can use

    <div [innerHTML]="theHtmlString | keepHtml"></div>
    
    0 讨论(0)
  • 2020-11-21 05:01

    Working in Angular v2.1.1

    <div [innerHTML]="variable or htmlString">
    </div>
    
    0 讨论(0)
提交回复
热议问题