首页 > 解决方案 > 角度样式绑定

问题描述

我正在做一个 Angular 8 项目,我想在 HTML 上绑定动态样式。我已经从 Angular 的官方文档中学到了一些东西。假设在我的 ts 文件中

colorCode: string = "#000000"

然后我想绑定到 HTML

<div class="card" [ngStyle]="{'background-color': colorCode}">
 ....
</div>
or
<div class="card" [style.background-color]="colorCode">
 ....
</div>

我非常理解这一点。但问题是当我想使用复杂的风格时

background-color: rgba($color:#000000, $alpha:0.5)

我已经尝试过这样,但它不起作用。我想要的只是动态颜色,其余的都是一样的。

this.colorCode = `rgba($color: ${colorValue}, $alpha: 0.5)`;

我不确定我必须做什么才能实现这一目标。

标签: cssangular

解决方案


创建一个接受颜色代码和不透明度的函数

  RGBA(hexCode, opacity) {
    let hex = hexCode.replace("#", "");

    if (hex.length === 3) {
      hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
    }

    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);

    return `rgba(${r},${g},${b},${opacity})`;
  }

并在模板中使用

<div [ngStyle]="{ 'color': RGBA('#fc7303',.7)}">
  Nilesh Patel
</div>
<div [style.background-color]="RGBA('#fc7303',.8)">
    Nilesh Patel-style
</div>

推荐阅读