2016-08-05 115 views
1

我想插入從服務器獲取的原始HTML,該HTML在一些標記中具有自定義屬性。 Angular2去掉我需要保留的未知屬性。我也非常樂於採用其他方式。Angular2原始HTML自定義屬性

目前angular2被嵌入到無角的頁面(不能改變),和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],[自定義]沒有成功

回答

3

您可以使用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

+0

太謝謝你了!正是我需要的 –

+1

不客氣!你也可以使用它作爲管道http://plnkr.co/edit/PZLeyT8qsrbP5WKNA8v0?p=preview – yurzui

+0

我喜歡「pipe way」歡呼隊友:) –