我有2个不同元素相同的ngStyle如何覆盖它们以保持代码干燥?

问题描述

我要覆盖ngstyle

            <p class="is-discount" [ngStyle]="{
                'background-color':
                  bike.discount > 70
                    ? 'red'
                    : bike.discount > 60
                    ? 'pink'
                    : bike.discount > 50
                    ? 'orange'
                    : null
              }">
              -{{ bike.discount }}%
            </p>
70 ? '红' :折扣> 60 ? '粉' :折扣> 50 ? '橙子' : 空值 }“> -{{bike.discount}}%
          <p [ngStyle]="{
              'color':
                bike.discount > 70
                  ? 'red'
                  : bike.discount > 60
                  ? 'pink'
                  : bike.discount > 50
                  ? 'orange'
                  : null
            }">
              {{
                bike.price - (bike.discount / 100) * bike.price
                  | currency: "EUR"
              }}
            </p>


      

解决方法

如果要在两个元素上使用相同的ngStyle。在该组件的.ts文件中创建一个变量:

myStyle = {
           'color':
            bike.discount > 70
            ? 'red'
            : bike.discount > 60
            ? 'pink'
            : bike.discount > 50
            ? 'orange'
            : null
          }

,然后可以在组件的.html文件中使用它,如下所示:

<p class="is-discount" [ngStyle]="myStyle">
  -{{ bike.discount }}%
</p>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...