3

I am having issue with if:true statement. I am unable to print Value 0 by using if:true statement and I dont know the reason exactly.

My requirement is to print 0 value by using if:true

Here is the code below

<template>

    <template if:true={value}>
        Value 0
    </template>

    <template if:true={value1}>
        Value 10
    </template>

</template>

JS file -

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {

    @track value = 0;
    @track value1 = 10;
}

Here is the link for your reference

Here is below screenshot of Output : enter image description here

  • you should use get variable to show the value – Sarvesh Apr 1 at 10:52
  • value = 0 does not evaluate to something truthy, value1 = 10 however does. So, value is NOT true. – Florian Heer Apr 1 at 10:56
5

The reason why if:true={value} equals false because 0 value is falsy. if:true directive expects boolean context, thus making type coercion. I'd recommend you to use getters. In your case, it can be looked like (if you expect the value property of number type):

@track value = 0;

get hasValue() {
   return typeof value === 'number' && isFinite(value);
}
<template if:true={hasValue}>
    {value}
</template>
| improve this answer | |
  • Nice answer, this is also how if value statement works in JavaScript. – Raul Apr 1 at 11:27
0

Use Getter to return true/false whether a value is equal to 0 or not

playgroung : link

HTML:

<template>
<template if:true={isTrue}>
    Value 0
</template>
<template if:true={value1}>
    Value 10
</template>
</template>

JS::

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {

    @track value = 0;
    @track value1 = 10;

    get isTrue(){
    return this.value == 0 ? true : false
   }
}
| improve this answer | |
  • return this.value == 0; The == operator already returns a true/false value. – sfdcfox Apr 1 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.