angulartypescriptng-classangular-ng-class

ngClass wrong answer


After going through a lot of questions , I have decided to ask this... The angular [ngClass] is working weird on the values for 10 , 24 , 100 . I don't know the reason behind it . Hoping you could all may help...

<div class="clearfix table-responsive mt-5">
      <table id="data_upload1" class=" table table-bordered table-striped table-hover selectParent">
        <thead>
          <tr>
              <th class="pointer">Obs</th>
              <th class="pointer">Date</th>
              <th class="pointer">Price</th>
              <th class="pointer">% Change</th>
            </tr>
        </thead>
        <tbody>
           <ng-container *ngFor="let price of priceList">
                            <tr> 
                                <td >{{price.serial}}</td>
                                <td >{{price.period}} </td>
                                <td ><input autofocus (blur)="updateValue($event, price.price)" type="text"
                                      [value]="value"  [(ngModel)] = "price.price" placeholder = ""   /></td>
                                <td [ngClass]="price.change >= price.hold  ? 'red': 'greenn'">{{price.change}} </td>
                            </tr>
              </ng-container> 
        </tbody>
      </table>
    </div>
    <button type="button" id="add_user_submit" class="btn btn-blue1 center-block">Save</button>
  </div>
</div>  

This is the JSON format from backend

0:{id: 101, price: 40, period: "2018-02-01", hold: "10", change: "n.a."}
1:{id: 102, price: 42, period: "2018-03-01", hold: "10", change: "5.00"}
2:{id: 103, price: 43, period: "2018-04-01", hold: "10", change: "2.38"}
length:3

The ngClass chooses wrong class on values like 10 , 100 , 24 Instead of greenn its showing the background in red color .


Solution

  • price.change >= price.hold
    

    You're comparing two strings.

    If you want to compare two numbers, I suggest you change your data to

    0:{id: 101, price: 40, period: "2018-02-01", hold: 10, change: null}
    1:{id: 102, price: 42, period: "2018-03-01", hold: 10, change: 5.00}
    2:{id: 103, price: 43, period: "2018-04-01", hold: 10, change: 2.38}
    

    And your comparison to

    price.change && price.change >= price.hold