前言
在開始本文的正文之前,我們先來看一下angular2中將帶標(biāo)簽的文本輸出在頁面上的相關(guān)內(nèi)容,為了系統(tǒng)性的防范XSS問題,Angular默認(rèn)把所有值都當(dāng)做不可信任的。 當(dāng)值從模板中以屬性(Property)、DOM元素屬性(Attribte)、CSS類綁定或插值表達(dá)式等途徑插入到DOM中的時候, Angular將對這些值進(jìn)行無害化處理(Sanitize),對不可信的值進(jìn)行編碼。
h3>Binding innerHTML</h3> <p>Bound value:</p> <p class="e2e-inner-html-interpolated">{{htmlSnippet}}</p> <p>Result of binding to innerHTML:</p> <p class="e2e-inner-html-bound" [innerHTML]="htmlSnippet"></p>
[innerHTML]="htmlSnippet"
這個屬性可以識別 HTML標(biāo)簽 但不識別標(biāo)簽中的屬性值
發(fā)現(xiàn)問題
大家都知道Angular 中有 innerHTML 屬性來設(shè)置要顯示的內(nèi)容,但是如果內(nèi)容包含 CSS 樣式,無法顯示樣式的效果。
比如:
public content: string = "<div style='font-size:30px'>Hello Angular</div>"; <p [innerHTML]="content"></p>
只會顯示 Hello World ,字體不會是 30px,也就是 CSS 樣式?jīng)]有效果。
解決方案
自定義一個 Pipe 來對內(nèi)容做轉(zhuǎn)換??聪旅娲a。
寫一個 HtmlPipe 類
import {Pipe, PipeTransform} from "@angular/core"; import {DomSanitizer} from "@angular/platform-browser"; @Pipe({ name: "html" }) export class HtmlPipe implements PipeTransform{ constructor (private sanitizer: DomSanitizer) { } transform(style) { return this.sanitizer.bypassSecurityTrustHtml(style); } }
在需要的模塊里面引入管道 HtmlPipe
@NgModule({ declarations: [ HtmlPipe ] })
在 innerHtml 中增加管道名字
<p [innerHTML]="content | html"></p>
這樣就可以顯示 content 的 CSS 樣式。
總結(jié)
Copyright ? 2019- 91gzw.com 版權(quán)所有 湘ICP備2023023988號-2
違法及侵權(quán)請聯(lián)系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市萬商天勤律師事務(wù)所王興未律師提供法律服務(wù)