Angular4中如何顯示內容的CSS樣式範例程式碼

來源:互聯網
上載者:User

本文主要給大家介紹了關於Angular 4中如何顯示內容的CSS樣式的相關資料,文中通過範例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。在開始本文的本文之前,我們先來看一下angular2中將帶標籤的文本輸出在頁面上的相關內容,為了系統性的防範XSS問題,Angular預設把所有值都當做不可信任的。 當值從模板中以屬性(Property)、DOM元素屬性(Attribte)、CSS類綁定或插值運算式等途徑插入到DOM中的時候, Angular將對這些值進行無害化處理(Sanitize),對不可信的值進行編碼。

h3>Binding innerHTML</h3><p>Bound value:</p><pclass="e2e-inner-html-interpolated">{{htmlSnippet}}</p><p>Result of binding to innerHTML:</p><pclass="e2e-inner-html-bound" [innerHTML]="htmlSnippet"></p>

[innerHTML]="htmlSnippet"

這個屬性可以識別 HTML標籤 但不識別標籤中的屬性值

發現問題

大家都知道Angular 中有 innerHTML 屬性來設定要顯示的內容,但是如果內容包含 CSS 樣式,無法顯示樣式的效果。

比如:

public content: string = "<p style='font-size:30px'>Hello Angular</p>";<p [innerHTML]="content"></p>

只會顯示 Hello World ,字型不會是 30px,也就是 CSS 樣式沒有效果。

解決方案

自訂一個 Pipe 來對內容做轉換。看下面代碼。

寫一個 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 樣式。

相關推薦;

Angular擷取項目中定義的json檔案

有什麼angularjs內建的方法

利用AngularJS完成表單驗證功能的介紹

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.