cssangularsassangular-ng-if

Angular: change style depending on *ngIf condition


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, ...)?


Solution

  • 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.