Angular HTML binding

后端 未结 21 2612
暖寄归人
暖寄归人 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:51

    Angular 2.0.0 and Angular 4.0.0 final

    For safe content just

    DOMSanitizer

    Potential unsafe HTML needs to be explicitly marked as trusted using Angulars DOM sanitizer so doesn't strip potentially unsafe parts of the content

    with a pipe like

    @Pipe({name: 'safeHtml'})
    export class Safe {
      constructor(private sanitizer:DomSanitizer){}
    
      transform(style) {
        return this.sanitizer.bypassSecurityTrustHtml(style);
        //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

    And docs: https://angular.io/api/platform-browser/DomSanitizer

    Security warning

    Trusting user added HTML may pose a security risk. The before mentioned docs state:

    Calling any of the bypassSecurityTrust... APIs disables Angular's built-in sanitization for the value passed in. Carefully check and audit all values and code paths going into this call. Make sure any user data is appropriately escaped for this security context. For more detail, see the Security Guide.

    Angular markup

    Something like

    class FooComponent {
      bar = 'bar';
      foo = `
    {{bar}}
    `;

    with

    won't cause Angular to process anything Angular-specific in foo. Angular replaces Angular specific markup at build time with generated code. Markup added at runtime won't be processed by Angular.

    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?

提交回复
热议问题