I have the same ngStyle for 2 different elements. How to overwrite them to keep the code DRY?

35 Views Asked by At

I want to overwrite 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 ? 'red' : bike.discount > 60 ? 'pink' : bike.discount > 50 ? 'orange' : null }"> -{{ 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>


      
1

There are 1 best solutions below

0
On

If you want to use the same ngStyle on both elements. Make a variable in your .ts file of the component:

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

and then you can use it in your .html file of your component like this:

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