css - 角度样式绑定
问题描述
我正在做一个 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)`;
我不确定我必须做什么才能实现这一目标。
解决方案
创建一个接受颜色代码和不透明度的函数
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>
推荐阅读
- laravel - Laravel,Vue Js 与 Vuetify 和 Vuelidate
- android - Android导航组件未显示正确的操作栏标题
- c# - EntityFramework核心错误“值不在预期范围内”
- python - 从 celery 功能进行推送通知
- ios - iOS - 占用水平 UIStackView 中的所有可用空间
- django - Django,如何获取forignkey相关对象的属性
- python - 如何通过 API Gateway 从 Jupyter Notebook 更新 DynamoDB?
- javascript - 打字稿和 ...args
- r - 如何使用 Shiny R 中的 downloadHandler 将多个 csv 文件下载到 zip 中
- html - 为 flexbox 列表设置固定间距