angularjs - 如何在 Angular 2 模板内显示获取的 html?

标签 angularjs angular angular2-template

我正在从远程服务器获取帖子的数据,帖子的数据包含带有 style 的 html和class属性(从所见即所得编辑器生成)。

我想按原样呈现 html 数据,而不对其进行过滤或清理。

我尝试使用这个方法:

<div [innerHTML]="post.body"></div>

但是 Angular 正在删除 style来自 html 的属性。

是否有办法保留 html 属性(即使它很危险)?

最佳答案

我认为你无论如何都必须这样做:

import { Component } from '@angular/core';
import { DomSanitizationService, SecurityContext, 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: DomSanitizationService){ }
  
  public get htmlProperty() : SafeHtml {
     return this._sanitizer.sanitize(SecurityContext.HTML, this._htmlProperty);
  }

}

您需要像 Angular 1 中那样清理 html。*

关于angularjs - 如何在 Angular 2 模板内显示获取的 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40379253/

相关文章:

javascript - 在 Angular 中,如何使用 $location.path 作为 $http.post 成功回调进行重定向

javascript - ionic http POST 不适用于服务器

模板中的 angular2 和 formControlName 值

Angular 2.0.1 AsyncPipe 不适用于 Rx Subject

css - Angular UI 网格 - 无法屏蔽分页控件

javascript - 错误 : Cannot find module 'entities/lib/decode_codepoint.js'

angular - 在功能模块中导入 HttpClientModule

javascript - 在 IOS 应用 Webview 中运行 Angular 应用

angular - 类正在使用 Angular 功能,但没有装饰。请添加一个显式的 Angular 装饰器

Angular2 - Keyup 需要澄清