Html 样式不适用于Angular 2 Typescript中的innerhtml
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44210786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
style not working for innerhtml in Angular 2 Typescript
提问by Chatra
I am passing html as innerHtml to my view. The below is my view
我将 html 作为innerHtml 传递给我的视图。以下是我的看法
<div [innerHTML]="someHtmlCode"></div>
if I pass the below code, it is working fine.
如果我通过下面的代码,它工作正常。
this.someHtmlCode = "<div><b>This is my HTML.</b></div>"
if I pass the below code which contain color, it is not working.
如果我传递以下包含颜色的代码,则它不起作用。
this.someHtmlCode = '<div style="background-color: blue;"><b>This is my HTML.</b></div>';
回答by Unsinkable Sam
This behavior you're getting is normal. The class added to innerHTML
is ignored because by default the encapsulation is Emulated
. Which means Angular prevents styles from intercepting inside and outside of the component.
You should change the encapsulation to None
in your component.
This way, you'll be able to define classes wherever you want: inside styles
or in a separate .css
, .scss
or .less
style-sheet (it doesn't matter) and Angular will add them to the DOM automatically.
你得到的这种行为是正常的。添加到的类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>';
}
}
回答by Shehram Tahir
I was also facing the same issue but after reading this below link I figured out the solution and it was done without using pipes
我也遇到了同样的问题,但在阅读下面的链接后,我找到了解决方案,并且它是在不使用管道的情况下完成的
Hope this will help you.
希望这会帮助你。
https://netbasal.com/angular-2-security-the-domsanitizer-service-2202c83bd90
https://netbasal.com/angular-2-security-the-domsanitizer-service-2202c83bd90
回答by Nehal
Instead of an inline style, I put the style in a class.
我将样式放在一个类中,而不是内联样式。
Not sure if using class
is an option for you or not, but here's a Plunker demo.
不确定使用class
是否适合您,但这里有一个 Plunker演示。
HTML:
HTML:
this.someHtmlCode = '<div class="demo"><b>This is my HTML.</b></div>'
CSS:
CSS:
.demo{
background-color: blue;
}