如何通过角度部分动态赋予模板样式?

Par*_*ain 5 css angular

我的 HTML 部分是:

<li *ngIf="action==null" id="list_icon"><a href="#" id="anchor"><i class={{icon}}></i> {{name}} {{color}}</a></li>
        <li *ngIf="action!=null" id="list_icon" class="active"><span id="anchor"><i class={{icon}}></i> {{name}}</span></li>
Run Code Online (Sandbox Code Playgroud)

和CSS是:

li a{
  background-color: red !important;
  border: 1px solid red !important;
}

li a:before{
border-left-color: red !important;
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,我想在Css中使用颜色,如下所示:

li a{background-color: {{color}} !important;}
Run Code Online (Sandbox Code Playgroud)

我的 {{color}} 数据来自我的控制器或类。{{color}} 显示在模板上,但在我的风格中不起作用。有没有其他方法可以通过角度数据动态给出样式。或者我的代码需要一些更正?

kei*_*thm 5

使用 Angular2,你可以直接更新背景颜色属性,如下所示: [style.background]="color"

所以你可以将你的更改<a>为: <a href="#" id="anchor" [style.background]="color">


Par*_*ain 2

我自己已经解决了我的问题。以下是我已完成的一些步骤。

  1. NgClass从 Angular2/Angular2导入指令。
  2. NgClass在 @view 注释中添加as 指令。
  3. 添加[ng-class]="color"到 HTML 部分。
  4. 将颜色类别添加到样式中。

完毕。

*重要的

angular2 提供了 ngClass 内置指令来设置文档样式。如需更多帮助,您可以在此处阅读整个教程https://angular.io/docs/js/latest/api/core/NgClass-class.html

- 更新 -

从 angular2 beta0.0 开始

  1. ng-class 更新为 ngClass
  2. ngClass 是从 angular2/common 导入的。
  3. ng-style 更新为 [ngStyle]。