如何在angular2中手动清理

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

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

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

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

您可以按如下方式清理HTML:
import { 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);
  }

}

Demo plunker here.

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

为此,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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")
                 .replace(/"/g,"&quot;").replace(/'/g,"&#039;");
  }
}

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

原文链接:https://www.f2er.com/angularjs/143549.html

猜你在找的Angularjs相关文章