天天看點

行内style在Angular10 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用法使用就可以啦,完美解決