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