Aashiq Rathnadas
Aashiq Rathnadas

Reputation: 525

Angular 2 - if condition getting true for all values

I have been stuck at a point, my if condition is returning true for all conditions, I am checking that a value is greater or not.

Code:

 hideAmountModal() {
    var self = this;
    self.home_delivery_charge = self.storeService.fetchHomedeliveryData(self.shopId);
    self.home_delivery_charge.subscribe((res: any) => {
      for (var i = 0; i < res.length; i++) {
        if (self.deliveryData.delivery_charge > res[i].amount) {
          self.check_delivery_charge = true;
          console.log('Deliverycharge',self.deliveryData.delivery_charge,'result',res[i].amount);
          console.log('deliver charge is greater',self.check_delivery_charge);
        }
        else if (self.deliveryData.delivery_charge < res[i].amount){
            self.check_delivery_charge = false;
        }
      }
    })
    self.DeliveryChargeValue = true
    self.selectAmountModal.hide();
  } 

From the console what I get is below:

enter image description here

Where have I gone wrong?

Upvotes: 0

Views: 105

Answers (4)

Niladri Basu
Niladri Basu

Reputation: 10614

Change your if condition from:

if (self.deliveryData.delivery_charge > res[i].amount)

To this:

if (Number(self.deliveryData.delivery_charge) > Number(res[i].amount))         

Doing this, you would be explicitly type-casting your input type into number.

Remember: You'll get NaN (Not-a-Number) if your input can't be converted to number type.

In case you don't want this behavior you could always use parseInt which uses Javascript's Number() function under-the-hood as shown here.

Upvotes: 1

plucins
plucins

Reputation: 153

You console.log only value when is true

Try add console.log here :

else if(self.deliveryData.delivery_charge < res[i].amount) {
  self.check_delivery_charge = false;
}

Upvotes: 0

Nandita Sharma
Nandita Sharma

Reputation: 13407

Try converting both values to number type

if (parseInt(self.deliveryData.delivery_charge) > parseInt(res[i].amount)) {
}

Upvotes: 1

miquelarranz
miquelarranz

Reputation: 894

Be careful because you are not handling the equal case, which you should include on the else if. Can you check that the values that you are comparing are numbers? This is probably the problem.

Upvotes: 0

Related Questions