样式不适用于Angular中的innerHTML [英] Style not working for innerHTML in Angular

查看:101
本文介绍了样式不适用于Angular中的innerHTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将html作为innerHtml传递给我的视图.下面是我的看法

I am passing html as innerHtml to my view. Below is my view

<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 contains color, it is not working.

 this.someHtmlCode = '<div style="background-color: blue;"><b>This is my HTML.</b></div>';

推荐答案

您得到的这种行为是正常的.添加到innerHTML的类将被忽略,因为默认情况下封装为Emulated.这意味着Angular会阻止样式在组件内部和外部进行拦截. 您应该在组件中将封装更改为None. 这样,您就可以在任何需要的地方定义类:在styles内部或在单独的.css.scss.less样式表中(无关紧要),Angular会将它们添加到DOM自动.

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.

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>';
  }
}

这篇关于样式不适用于Angular中的innerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆