我有一个textarea,用户将输入一些文本.文本不能是JavaScript或HTML等.我想手动清理数据并将其保存为字符串.
我无法弄清楚如何使用DomSanitizationService来“手动”清理我的数据.
如果我在页面上{{textare_text}},那么数据将被正确清理.
如何手动将其设置为我拥有的字符串?
您可以按如下方式清理HTML:
原文链接:https://www.f2er.com/angularjs/143549.htmlimport { Component,SecurityContext } from '@angular/core'; import { DomSanitizer,SafeHtml } from '@angular/platform-browser'; @Component({ selector: 'my-app',template: ` <div [innerHTML]="_htmlProperty"></div> ` }) export class AppComponent { _htmlProperty: string = 'AAA<input type="text" name="name">BBB'; constructor(private _sanitizer: DomSanitizer){ } public get htmlProperty() : SafeHtml { return this._sanitizer.sanitize(SecurityContext.HTML,this._htmlProperty); } }
根据您的评论,您实际上想要逃避而不是消毒.
为此,check this plunker,where we have both escaping and sanitization.
import { Component,template: `Original,using interpolation (double curly braces):<b> <div>{{ _originalHtmlProperty }}</div> </b><hr>Sanitized,used as innerHTML:<b> <div [innerHTML]="sanitizedHtmlProperty"></div> </b><hr>Escaped,used as innerHTML:<b> <div [innerHTML]="escapedHtmlProperty"></div> </b><hr>Escaped AND sanitized used as innerHTML:<b> <div [innerHTML]="escapedAndSanitizedHtmlProperty"></div> </b>` }) export class AppComponent { _originalHtmlProperty: string = 'AAA<input type="text" name="name">BBB'; constructor(private _sanitizer: DomSanitizer){ } public get sanitizedHtmlProperty() : SafeHtml { return this._sanitizer.sanitize(SecurityContext.HTML,this._originalHtmlProperty); } public get escapedHtmlProperty() : string { return this.escapeHtml(this._originalHtmlProperty); } public get escapedAndSanitizedHtmlProperty() : string { return this._sanitizer.sanitize(SecurityContext.HTML,this.escapeHtml(this._originalHtmlProperty)); } escapeHtml(unsafe) { return unsafe.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">") .replace(/"/g,""").replace(/'/g,"'"); } }
上面使用的HTML escaping function与angular code does相同的字符(不幸的是,它们的转义功能不公开,所以我们不能使用它).