文章内容
2020/7/26 14:47:51,作 者: 黄兵
Angular [innerHTML] styles不起作用
最近在使用Angular [innerHTML]获取后端内容,但是scss文件定义内容样式,不起作用,具体代码如下:
<div class="rich-text" [innerHTML]="html">
</div>
styles.scss:
.rich-text, p {
line-height: 1.625;
font-size: 16px;
letter-spacing: 0;
}
.rich-text > p {
font-size: inherit;
line-height: inherit;
}
p + p {
margin-top: 16px;
}
.rich-text img {
max-width: 100%;
}
但是样式却不起作用,截图截图如下:
因为默认情况下,Angular将[innerHTML]封装为Emulated。这意味着Angular会阻止样式在组件内部和外部进行拦截。您应该将封装更改为None。这样一来,你就可以定义任何你想要类:styles或在一个单独的.css,.scss或者.less样式表和Angular将它们自动添加到DOM。
示例代码如下:
import { Component, ViewEncapsulation } from '@angular/core';
@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>';
}
}
这样定义的样式即可。
参考资料:
1、style not working for innerhtml in Angular 2 Typescript [duplicate]
黄兵个人博客原创。
评论列表