skip to Main Content

I hoping someone can explain this to me. Why does the %ngIf as well as the else seem to always negate to true unless I’m doing something totally wrong.

This is the scenario:
I have a icon if the array length is >=0 it will turn the background color to pink
else the background color of the icon will be white.

No matter how I change the scenario it still negates to true. I deleted the array and the
icon still remained solid pink. I added an else it would choose the else even the if *ngIf is true. So, not sure what’s going on here.

Here are some of the things I tried

          <span *ngIf="wishitems.length >=0" class="fas fa-heart float-right" aria- 
          hidden="true"></span>


        <span *ngIf="wishitems.length >=0" class="fas fa-heart float-right" aria- 
        hidden="true" ngIfElse="wishitems.length == -1" class="far fa-heart float-left" 
         aria-hide="true"></span>

         <span *ngIf="wishitems.length >=0" class="fas fa-heart float-right" aria- 
         hidden="true"></span>
    
          <span *ngIf="wishItems.length <0" class="far fa-heart float-right" aria- 
          hide="true"></span>

I recall reading some where that the *ngIf didn’t like negative numbers. Any help in
pointing me in the right direction would be great! Thanks in advance.

2

Answers


  1. Your first *ngIf works if wishitems is an array.

    To test what’s going on, change wishitems to an array of number like that:

    wishitems: Array<number> = [1];
    

    And your html to:

    <span *ngIf="wishitems.length >=0" aria-hidden="true">Test</span>
    

    Then you will start to see Test in your browser.

    Login or Signup to reply.
  2. Restructure your *ngIf to handle the negation part as well. Currently, the truth scenario is being handled. Also, ensure the correct condition is also used to evaluate in the template.

    Refer the code below:

    <ng-template #elseTemplate>
      <span class="far fa-heart float-right" aria-hidden="true"></span>
    </ng-template>
    
    <span *ngIf="wishitems.length > 0; else elseTemplate" class="fas fa-heart float-right" aria-hidden="true"></span>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search