繁体   English   中英

Angular6 ngStyle 动态应用样式

[英]Angular6 ngStyle to apply style dynamically

我正在使用 angular6 并尝试通过角度表中的内联样式来实现背景颜色。 如果我对值进行硬编码,背景颜色会发生变化,但如果我尝试将其放入变量中,它会保持不变。

模板:

<ng-container matColumnDef="color">
  <th mat-header-cell *matHeaderCellDef mat-sort-header> color </th>
  <td mat-cell *matCellDef="let element" [ngStyle]="{'background-color':'#element.color'}"> #{{element.color}} </td>
</ng-container>

您可以像那样使用仅设置一种样式然后尝试像那样使用

public bgcolor = "red";

注意这里没有使用 (-) 而不是使用驼峰式风格

 [style.backgroundColor]="bgcolor"

第二种方式用于多个

public bgcolor = {
    backgroundColor:"orange"
};

[ngStyle]="bgcolor"

为你那样使用的风格

[ngStyle]="{ backgroundColor:'#' + element.color }"



<ng-container matColumnDef="color">
  <th mat-header-cell *matHeaderCellDef mat-sort-header> color </th>
  <td mat-cell *matCellDef="let element" [ngStyle]="{ backgroundColor:'#' + element.color }" > #{{element.color}} </td>
</ng-container>

如果你想为背景色赋值变量(selectedElementColor)值,你可以这样做

[ngStyle]="{'backgroundColor': selectedElementColor}"

如果您根据条件分配此值,则可以按如下方式使用条件

[ngStyle]="value === selectedValue && {'backgroundColor': selectedElementColor}

确保您使用的是属性 backgroundColor 而不是 background-color。

<span  [ngStyle]="{'background-color': item.color}"> </span>

页面 service.ts ::

  return {
    'toolbarTitle': 'My Pins',
    'items': [
        {
            'id': 1,
            'color' : 'red',
        },
    ]
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM