Search code examples
cssangularng-class

angular 9: Multiple conditions on ngClass inside a ngFor


I'm having some issues trying to print the typical star-rating widget in my page using angular. Probably there will be an easier way to show them using css but for now i wanted to do it by code.

<i *ngFor="let star of this.stars" [ngClass]="{
    'score__star fas fa-star': star === 'full',
    'score__star fas fa-star-half-alt': star === 'half', 
    'score__star far fa-star': star === 'empty'
    }"></i>

this is the code of the widget and this is the content of the array of stars:

(5) ["full", "full", "half", "empty", "empty"]

i'm not sure why, chrome draws properly the first 2 but not the others. From what i have seen in the debugger there are parts of the class that are missed...

<i _ngcontent-lqd-c56="" ng-reflect-ng-class="[object Object]" class=""></i>
<i _ngcontent-lqd-c56="" ng-reflect-ng-class="[object Object]" class=""></i>
<i _ngcontent-lqd-c56="" ng-reflect-ng-class="[object Object]" class="fas fa-star-half-alt"></i>
<i _ngcontent-lqd-c56="" ng-reflect-ng-class="[object Object]" class="score__star far fa-star"></i>
<i _ngcontent-lqd-c56="" ng-reflect-ng-class="[object Object]" class="score__star far fa-star"></i>

Any idea of what i'm missing? I also tried to mix class and ngClass to split the common part of the style but i had the same problem.

Thanks a lot!


Solution

  • I see one workaround for this problem. Could you change your classes, e.g:

    getClasses(star) {
      return {
        'full' : star === 'full',
        'half' : star === 'half', 
        'empty' : star === 'empty' 
    }}
    

    Also I'm not sure If you know this but you can pass method to ngClass directive

    <i *ngFor="let star of stars" [ngClass]="getClasses(star)">
      {{star}}
    </i>