行内style在Angular10 TypeScript中的innerHtml中不起作用

26 篇文章 2 订阅

项目中用到了富文本编辑器, 编辑器把样式都返回在了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用法使用就可以啦,完美解决

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值