简体   繁体   English

AngularJs清理并显示html

[英]AngularJs sanitizing and displaying html

I am trying to display dynamically html inside a div. 我正在尝试在div中动态显示html。 However the div ng-bind-html does not display at all (on firefox, chrome and safari). 但是div ng-bind-html根本不显示(在Firefox,chrome和safari上)。

Looking at the other posts of this website I saw that I have to include ngSanitize. 查看该网站的其他帖子,我发现我必须包括ngSanitize。

I found this snippet here https://www.npmjs.com/package/angular-sanitize : 我在这里https://www.npmjs.com/package/angular-sanitize找到了这个片段:

angular.module('myApp', ['ngSanitize']);

However I do not know where I should write this code ... Do you have any idea how I could do it ? 但是我不知道我应该在哪里写这段代码……你知道我该怎么做吗?

Thank you very much ! 非常感谢你 !

Here is my code : 这是我的代码:

Code in the component.ts: component.ts中的代码:

import { Component, OnInit, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-player-filter',
  templateUrl: './player-filter.component.html',
  styleUrls: ['./player-filter.component.css']
})
export class PlayerFilterComponent implements OnInit {

  text = '<h1>Test</h1><script></script>';
  text_sanitized: SafeHtml;
  constructor(private _sanitizer: DomSanitizer) { }

  ngOnInit() {
      this.text_sanitized = this.htmlProperty;
  }

  public get htmlProperty(): SafeHtml {
      return this._sanitizer.sanitize(SecurityContext.HTML, this.text);
  }

}

Code in the component.html: component.html中的代码:

<div ng-bind-html="text_sanitized"></div>
Normal: {{text}} Sanitized: {{text_sanitized}}

Output on firefox: 在Firefox上输出:

Normal: <h1>Test</h1><script></script> Sanitized: <h1>Test</h1>

Output console: 输出控制台:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

The console output shows that the sanitizing operation happenned (confirmed by the output sanitized that got rid of the script). 控制台输出显示发生了清理操作(由清除了脚本的清理后的输出确认)。 Wierd thing, there is no error shown in the console from having unsafe html displayed... 奇怪的是,显示不安全的html不会在控制台中显示错误...

The 'ng-bind-html' belongs to angularJS(older version before angular 2+) so its not suppose to work or display anything with Angular 6. 'ng-bind-html'属于angularJS(angular 2+之前的旧版本),因此它不能与Angular 6一起使用或显示任何内容。

Use [innerHTML] instead as mentioned in Agular Documentation : 使用[innerHTML]代替,如Agical Documentation中所述

<div [innerHTML]="text_sanitized"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM