:

后端 未结 9 1265
情深已故
情深已故 2020-11-27 12:54

Since upgrading to the latest Angular 2 release candidate, my img tags:



        
9条回答
  •  攒了一身酷
    2020-11-27 13:31

    Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

    So if you are manipulating DOM directly and inserting content it, you need to sanitize it otherwise Angular will through errors.

    I have created the pipe SanitizeUrlPipe for this

    import { PipeTransform, Pipe } from "@angular/core";
    import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
    
    @Pipe({
        name: "sanitizeUrl"
    })
    export class SanitizeUrlPipe implements PipeTransform {
    
        constructor(private _sanitizer: DomSanitizer) { }
    
        transform(v: string): SafeHtml {
            return this._sanitizer.bypassSecurityTrustResourceUrl(v);
        }
    }
    

    and this is how you can use

    
    

    If you want to add HTML, then SanitizeHtmlPipe can help

    import { PipeTransform, Pipe } from "@angular/core";
    import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
    
    @Pipe({
        name: "sanitizeHtml"
    })
    export class SanitizeHtmlPipe implements PipeTransform {
    
        constructor(private _sanitizer: DomSanitizer) { }
    
        transform(v: string): SafeHtml {
            return this._sanitizer.bypassSecurityTrustHtml(v);
        }
    }
    

    Read more about angular security here.

提交回复
热议问题