【问题标题】:Angular2 raw html custom attributeAngular2原始html自定义属性
【发布时间】:2016-08-05 14:58:21
【问题描述】:

我想插入从服务器获得的原始 HTML,它在某些标签中具有自定义属性。 Angular2 去除了我需要保留的未知属性。我也对其他方式持开放态度。

目前 angular2 被嵌入到非 Angular 页面中(无法更改),并且 jQuery 选择不基于自定义属性的标签,所以我需要保留它们

import {Component} from '@angular/core'

@Component({
  selector: 'my-app',
  template: `<div [innerHTML]="rawHtml">[custom] attribute not present</div>`,
})
export class App {
  rawHtml = '<span class="class" custom="custom">Text</span>';
}

http://plnkr.co/edit/sKVHUubK0ofUfmSdR5gO?p=preview

仅供参考,我试过 attr.custom, [attr.custom], [custom] 没有成功

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用DomSanitizationService 来做到这一点

    import { DomSanitizationService } from '@angular/platform-browser';
    
    @Component({
      selector: 'my-app',
      providers: [],
      template: `
        <div [innerHTML]="rawHtml"></div>
      `,
      directives: []
    })
    export class App {
      private _rawHtml: string = '<span class="class" custom="custom">Text</span>';
    
      public get rawHtml() {
         return this._sanitizer.bypassSecurityTrustHtml(this._rawHtml);
      }
    
      constructor(private _sanitizer: DomSanitizationService) { }
    }
    

    Updated Plunker

    【讨论】:

    猜你喜欢
    • 2020-02-11
    • 2015-11-17
    • 2016-06-30
    • 2018-01-08
    • 2017-08-30
    • 2019-05-14
    • 2016-09-07
    • 2011-07-19
    • 2013-01-20
    相关资源
    最近更新 更多