3

I'm aware that I can do something like this:

<ng-container *ngIf="user.age<18;else over">
  <div class="some-section" style="background-color: red;">
    [...]
  </div>
</ng-container>
<ng-template #over>
  <div class="some-section" style="background-color: blue;">
    [...]
  </div>
</ng-template>

Although this works, it is duplicate code. Is there a way to change only the style so that there's no duplicates (scss, other angular tools, ...)?

VLAZ
  • 26,331
  • 9
  • 49
  • 67

6 Answers6

2

Too change a style depending on a condition, you only have to use this:

[style.xxx]="expression"

Example:

<div class="some-section" [style.backgroundColor]="age < 18 ? 'red' : 'blue'">

Or via function, for more "complex" calculations without messing up HTML

<div class="some-section" [ngStyle]="calculateStyles()">

calculateStyles() {
   if (user.age<18) { 
      return "background-color: red";
   } else {
      return "background-color: blue";
   }
}

And then, the "better" way to manage your styles depending on conditions, using a class instead of just just "styles":

[ngClass]="expression"

Example:

<div class="some-section" [ngClass]="{'classACSS': user.age<18, 'classBCSS': user.age>=18}"

.classACSS {
background-color: red;
}

.classBCSS {
background-color: blue;
}

I leave you HERE the doc with a more detailed explanation of all of this.

2

Since the question title mentions style we'll only apply styles using [ngStyle]

To only change style, you can use the [ngStyle] instead of [ngClass] which adds a class instead of styles. Using your code as an example it should look like this:

<div class="some-section" [ngStyle]="{'background-color': (user.age < 18) ? 'red' : ((user.age >= 18) ? 'blue' : null) }">
  [...]
</div>

Also using [ngStyle] and [ngClass] for adding styles and classes will help you bind a string of classes, an array of strings, or an object. For more complex scenarios.

HassanMoin
  • 2,024
  • 1
  • 6
  • 16
0

The simplest way to do that:

  <div class="some-section"
       [style.backgroundColor]="age > 18 ? 'red' : 'blue'">
    [...]
  </div>

stackblitz

Meddah Abdallah
  • 654
  • 1
  • 7
  • 25
0

This is one way to do it check out this stackblitz

<div class="some-section" style="background-color: {{age < 18 ? 'red' : 'blue'}}">
  Test
</div>
alphapilgrim
  • 3,761
  • 8
  • 29
  • 58
0

<div class="some-section" [style.backgroundColor]="age < 18 ? 'red' : 'blue'">
-3
<div class="some-section" *ngIf="user.age<18" style="background-color:red;">
  [...]
</div>
<div class="some-section" *ngIf="user.age>18" style="backdrop-color:blue">
  [...]
</div>
Robin Chauhan
  • 71
  • 4
  • 12