行內style在angular2 TypeScript中的innerHtml中不起作用

項目中用到了富文本編輯器, 編輯器把樣式都返回在了p標籤的style中,例如

<p style="font-size: 20px;color: #00acc1;line-height: 18px;">
    <span style="font-size: 18px;color: #64c159;font-weight: bold"></span>
</p>

不幸的是,當我把這段內容賦值給一個div的innerHtml時,結果什麼樣還是什麼樣,還有的樣式沒有,style還是style,

<p style="font-size: 20px;color: #00acc1;line-height: 18px;">
  <span style="font-size: 18px;color: #64c159;font-weight: bold"></span>
</p>

後來在stackoverflow找到原因
原來Angular2中的typescript會自動忽略掉標籤中的style屬性,也就是說賦值innerHtml的時候就必須吧相應的樣式寫成class。就像這樣

@Component({
  selector: 'example',
  styles: ['.demo {background-color: blue}'],
  template: '<div [innerHTML]="someHtmlCode"></div>',
  encapsulation: ViewEncapsulation.None,
})
export class Example {
  private someHtmlCode = '';

  constructor() {
    this.someHtmlCode = '<div class="demo"><b>This is my HTML.</b></div>';
  }
}

很明顯,我提取不到<p></p>中的style,那就得另想辦法。
後來尋尋覓覓,找到了一個方法,就是寫一個safeHTMLPipe。
解決辦法

import {Pipe, PipeTransform} from '@angular/core'
import {DomSanitizer} from '@angular/platform-browser'
/**
 * @desc 爲了不使html去掉其中的style 樣式
 */
@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
  }

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html)
  }
}

然後按照正常的pipe用法使用就可以啦,完美解決

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