如何在angular2中手动清理

前端之家收集整理的这篇文章主要介绍了如何在angular2中手动清理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个textarea,用户将输入一些文本.文本不能是JavaScript或HTML等.我想手动清理数据并将其保存为字符串.

我无法弄清楚如何使用DomSanitizationService来“手动”清理我的数据.

如果我在页面上{{textare_text}},那么数据将被正确清理.

如何手动将其设置为我拥有的字符串?

您可以按如下方式清理HTML:
  1. import { Component,SecurityContext } from '@angular/core';
  2. import { DomSanitizer,SafeHtml } from '@angular/platform-browser';
  3.  
  4. @Component({
  5. selector: 'my-app',template: `
  6. <div [innerHTML]="_htmlProperty"></div>
  7. `
  8. })
  9. export class AppComponent {
  10.  
  11. _htmlProperty: string = 'AAA<input type="text" name="name">BBB';
  12.  
  13. constructor(private _sanitizer: DomSanitizer){ }
  14.  
  15. public get htmlProperty() : SafeHtml {
  16. return this._sanitizer.sanitize(SecurityContext.HTML,this._htmlProperty);
  17. }
  18.  
  19. }

Demo plunker here.

根据您的评论,您实际上想要逃避而不是消毒.

为此,check this plunker,where we have both escaping and sanitization.

  1. import { Component,template: `Original,using interpolation (double curly braces):<b>
  2. <div>{{ _originalHtmlProperty }}</div>
  3. </b><hr>Sanitized,used as innerHTML:<b>
  4. <div [innerHTML]="sanitizedHtmlProperty"></div>
  5. </b><hr>Escaped,used as innerHTML:<b>
  6. <div [innerHTML]="escapedHtmlProperty"></div>
  7. </b><hr>Escaped AND sanitized used as innerHTML:<b>
  8. <div [innerHTML]="escapedAndSanitizedHtmlProperty"></div>
  9. </b>`
  10. })
  11. export class AppComponent {
  12. _originalHtmlProperty: string = 'AAA<input type="text" name="name">BBB';
  13. constructor(private _sanitizer: DomSanitizer){ }
  14.  
  15. public get sanitizedHtmlProperty() : SafeHtml {
  16. return this._sanitizer.sanitize(SecurityContext.HTML,this._originalHtmlProperty);
  17. }
  18.  
  19. public get escapedHtmlProperty() : string {
  20. return this.escapeHtml(this._originalHtmlProperty);
  21. }
  22.  
  23. public get escapedAndSanitizedHtmlProperty() : string {
  24. return this._sanitizer.sanitize(SecurityContext.HTML,this.escapeHtml(this._originalHtmlProperty));
  25. }
  26.  
  27. escapeHtml(unsafe) {
  28. return unsafe.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")
  29. .replace(/"/g,"&quot;").replace(/'/g,"&#039;");
  30. }
  31. }

上面使用的HTML escaping functionangular code does相同的字符(不幸的是,它们的转义功能不公开,所以我们不能使用它).

猜你在找的Angularjs相关文章