2017年2月9日 星期四

[Angular] Use Sanitizer to ensure safe html string

 Angular    Sanitizer     Directive  


Introduction


In AngularJS, you may use $sanitize to ensure the safe html.
In Angular2, we will use Sanitizer class to do the same thing, the following is a simple sample and we will create a directive to enhance [innerHtml].


Environment
angular 2: 2.1.0


Implement


How to use Sanitizer

app.component.ts

import { Sanitizer, SecurityContext } from '@angular/core';

constructor(private sanitizer: Sanitizer) {
    let safeHtml = this.sanitizer.sanitize(SecurityContext.HTML, "<script>alert('I am bad!')</script>");
}


HTML

<input type="text" [(ngModel)]="safeHtml" />


Result:







Directive


import { Directive, ElementRef, Input, ViewContainerRef, Compiler, OnChanges, Sanitizer, SecurityContext } from '@angular/core';

@Directive({
    selector: '[safe-html]'
})
export class SafeHtml implements OnChanges {
    @Input() html: string;

    constructor(private elementRef: ElementRef, private sanitizer: Sanitizer) {


    }

    ngOnChanges() {

        if (this.html) {
            this.elementRef.nativeElement.innerHTML =
                this.sanitizer.sanitize(SecurityContext.HTML, this.html);
        }
    }
}


Usage

<div safe-html [html]="htmlStr"></div>



Reference


沒有留言:

張貼留言