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

时间:2015-10-31 07:17:46

标签: 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>

和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}}数据来自我的控制器或类。 {{color}}显示在模板上,但不会以我的风格工作。有什么其他方法可以通过角度数据动态地给出样式。或者我的代码需要更正?

4 个答案:

答案 0 :(得分:2)

使用Angular2,您可以直接更新background-color属性,如下所示: [style.background]="color"

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

答案 1 :(得分:1)

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

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

    *重要

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

    - 更新 -

    of angular2 beta0.0

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

请尝试使用//for your custom route that starts with "myText" routes.MapRoute( name: "MyText", url: "myText/{controller}/{action}/{id}", defaults: new { controller = "MyController", action = "MyAction", id = UrlParameter.Optional } ); //for other normal routes routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 。您可以通过以下方式设置样式:

ngStyle

有关详情,请查看文档:{​​{3}}