【问题标题】:Include css styles sent by a backend into a component将后端发送的 CSS 样式包含到组件中
【发布时间】:2017-01-14 16:30:41
【问题描述】:

我正在尝试将后端发送的 css 样式包含到我的组件模板中。

我的服务器响应如下所示:

serverResponse: {
   content: '<div class="myClass classX">hello world</div>',
   styles: '.myClass{color:red} .classX{...}  ....';
}

(我知道从后端获取 css 样式不是一个好主意,但不幸的是我无法更改它 ;-)

我的组件模板如下所示:

<style>
   <!-- serverResponse.styles should be in here. But how? -->
</style>
<div [innerHTML]="serverResponse.content">
   <!-- Binding to innerHTML works! -->
</div>

我已经在我的组件中将封装设置为“ViewEncapsulation.None”,以启用&lt;style&gt; 元素的样式。

我已经尝试过是这样的:

<style [textContent]="serverResponse.styles">

但是绑定到 textContent 不起作用...

非常感谢您的帮助!

【问题讨论】:

  • 也许你应该动态load entry component
  • 为什么&lt;style [innerHTML]="serverResponse.styles"&gt; 不起作用?你得到什么错误?
  • @MrLister 刚刚没有创建样式元素

标签: angular angular2-template


【解决方案1】:

首先,您应该使用来自服务器响应的样式更新您的类属性。

然后使用样式绑定与您的模板绑定您的样式类属性。

【讨论】:

  • 我同意这是一种更好的方法,我强烈推荐这种方法,而不是尝试将 CSS 动态添加到页面样式中。
  • “更新你的类属性”是什么意思?我从后端获得的样式可能包含多个类......例如serverResponse.styles = ".myClass{...} .classX{...}"
【解决方案2】:

我有点犹豫,因为我认为在页面上附加单独的 css 规则不是好的做法,但我会尝试回答这个问题。

$(function() {

  function handleElementResponse( html, css ) {
    console.log( $("style") );
    
    $("style").append( css );
    $("#mydiv").append( html );
  };
  
  handleElementResponse(
    "<div class=\"myClass\">hello world</div>",
    ".myClass{color:red}"
    );
    handleElementResponse(
    "<div class=\"myClass2\">hello world 2</div>",
    ".myClass2{color:blue}"
    );
});
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <style></style>
</head>

<body>
  <div id="mydiv">
     <span class="someClass">Hello</span>
  </div>
</body>
</html>

我的拙见是,您应该:

  1. 直接使用“style”属性将样式添加到元素中
  2. 如果可能,请事先定义样式并将类应用到 html 元素。

希望对你有帮助

【讨论】:

  • 好吧,这可能行得通...但我想知道是否有更特定于 Angular2 的解决方案。
猜你喜欢
  • 2014-01-05
  • 2022-01-23
  • 2020-02-17
  • 2011-07-08
  • 1970-01-01
  • 2016-05-15
  • 2021-12-08
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多