【问题标题】:Angular:add dynamic classAngular:添加动态类
【发布时间】:2018-05-09 19:43:42
【问题描述】:

我有一个 json,它会返回我的边框颜色,这将应用于跨度。 JSON是 文件 = [ { '边框颜色':'红色' } ]

如何动态应用类?

我的html很简单

<div *ngFor="let file of File">
 <span dynamicClassComesHere></span>

【问题讨论】:

  • 这对你有用吗?

标签: angular css primeng


【解决方案1】:

试试这个,

HTML:

<div *ngFor="let file of File">
 <span [style.border-color]="file.borderColor"></span>
</div>

【讨论】:

    【解决方案2】:

    应该是-

     <span [ngClass]='dynamicClass'></span>
    

    working example

    除此之外,根据官方文档

    ,还有多种方法可以做到这一点
    <some-element [ngClass]="'first second'">...</some-element>
    
    <some-element [ngClass]="['first', 'second']">...</some-element>
    
    <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
    
    <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
    
    <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
    

    Read more about ngClass here

    【讨论】:

    • 这在我的情况下不起作用,下面的评论有效
    • @Anna 你检查过我的工作示例吗?下面的评论是动态添加样式而不是类。我认为问题是关于动态添加类
    • 是的,我检查你的工作前,相同的代码在我的工作区中没有工作
    • @Anna 那么很可能错误来自您的代码的其他地方,请检查!
    【解决方案3】:

    因为它只是单一的样式,所以像这样使用ngStyle

    const style = {'borderColor':'red'};//ts file 
    <span [ngStyle]="style"></span >
    <span [ngStyle]="{'borderColor':getBorderColor()}"></span >
    

    你的情况

    <div *ngFor="let file of File">
     <span [ngStyle]="JSON.stringify(file)"></span>
    

    也可以这样

        <span [style.borderColor]="getBorderColor()">
        getBorderColor() {
         style =  JSON.parse(`{ 'borderColor':'red' }`);
         return style.borderColor;
       }
    

    你的情况

    <div *ngFor="let file of File">
     <span [style.borderColor]="file.borderColor"></span>
    

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 2019-04-26
      • 2017-07-17
      • 2019-08-30
      相关资源
      最近更新 更多