Angular用[innerHTML]顯示html文本,保留富文本在html中的行內style樣式(SafeHtmlPipe)

項目中經常需要用到富文本組件,我使用的一個輕量級的富文本組件是Trumbowyg,壓縮後文件很小。編輯文本後,顯示也是一個問題。

一段文字在輕量級文本編輯器中展示如下:富文本
在ts中模擬此富文本:

import {Component, OnInit} from '@angular/core'

@Component({
  selector: 'app-inner-html',
  templateUrl: './inner-html.component.html',
  styleUrls: ['./inner-html.component.less']
})
export class InnerHtmlComponent implements OnInit {
  richText = `
  <p>1、<strong style="color: rgb(192, 80, 77);">ECMAScript</strong> 和 
  <strong style="color: rgb(192, 80, 77);">JavaScript</strong> 的關係
</p>
<p>
  <em>一個常見的問題是,<span style="color: rgb(192, 80, 77);">ECMAScript</span>
  和<span style="color: rgb(192, 80, 77);">JavaScript</span> 到底是什麼關係?
  </em>
</p>
  `

  constructor() {
  }

  ngOnInit(): void {
  }

}

html中顯示:

<h3>顯示html文本</h3>
<div class="text" [innerHTML]="richText"></div>

效果:
效果
會發現跟在文本編輯器中表現不一致,打開 瀏覽器 檢查-Elements 查看源碼發現內聯的style消失了,
html源碼
這時我們需要添加一個safeHtmlPipe,並在AppModule的declarations數組中聲明:

// safe-html.pipe.ts
import {Pipe, PipeTransform} from '@angular/core'
import {DomSanitizer} from '@angular/platform-browser'

/*
 * 爲了不使html去掉其中的style 樣式
 */
@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
  }

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html)
  }
}
import {SafeHtmlPipe} from './pipes/safe-html.pipe'

@NgModule({
  declarations: [
    ...
    SafeHtmlPipe,
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

修改inner-html.component.html;

<div class="text" [innerHTML]="richText | safeHtml"></div>

最終效果:
最終效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章