如何通过 angular 部分动态地为模板提供样式?

how to give style dynamically to template via angular part?

我的 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>

和css是:

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

li a:before{
border-left-color: red !important;
}

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

li a{background-color: {{color}} !important;}

我的{{color}}数据来自我的控制器或class。 {{color}} 显示在模板上,但在我的风格中不起作用。是否有任何其他方法可以通过 angular 数据动态提供样式。或者我的代码需要一些更正?

使用 Angular2,您可以像这样直接更新背景颜色属性: [style.background]="color"

因此您可以将 <a> 更改为: <a href="#" id="anchor" [style.background]="color">

您可以为每种颜色创建一个 class 并使用它们:

JSFiddle

HTML:

<li id="list_icon"><a href="#" id="anchor" ng-class="color"><i class={{icon}}></i> {{name}} {{color}}</a></li>

CSS:

.green {
    background-color: green !important;
    border: 1px solid green !important;
}

JS:

app.controller('dummy', ['$scope', function ($scope) {
    $scope.color = 'green';
}]);

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

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

完成。

*重要

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]。

请尝试 ngStyle。您可以通过以下方式设置样式:

<a ng-style="{'background-color': color}">Sample Text</a>

更多信息请查看文档:https://docs.angularjs.org/api/ng/directive/ngStyle