0

I have below code where hold.Property__r.Holds__c is a numeric value due to which I am getting error. Can someone suggest how we convert this field to bool

<div if:true={hold.Property__r.Holds__c} class="slds-col slds-size_1-of-2">
                        <lightning-badge class="slds-text-heading_medium" label="On Hold"></lightning-badge>
                    </div>
                    <div if:false={hold.Property__r.Holds__c} class="slds-col slds-size_1-of-2">
                        <lightning-badge class="slds-text-heading_medium" label="Error - Incorrect Hold Status"></lightning-badge>
                    </div>
3
  • 3
    try using getters and setters, manually processing data Commented May 30, 2022 at 7:20
  • 1
    And such a getter could be as simple as return !!this.hold.Property__r.Holds__c (though perhaps with a safe navigation operator in case any part of the path is null like return !!this.hold?.Property__r?.Holds__c).
    – Phil W
    Commented May 30, 2022 at 7:23
  • @OlehBerehovskyi I dont have much experience on this.. Could you please elaborate on the context above Commented May 30, 2022 at 7:30

1 Answer 1

3

As @OlehBerehovskyi said, use a getter that coerces the number into a boolean. The assumption here is that you care if the "holds" value is non-zero.

First, add the following getter to your LWC:

get holds() {
    return !!this.hold?.Property__r?.Holds__c;
}

And update your template to use:

<div if:true={holds} class="slds-col slds-size_1-of-2">
   ...

This works by:

  1. Using "!!" to get the "truthiness" of a number; it first does a "not" of a number, which is a boolean indicating whether it is zero (the "falsiness"), then notting that again to indicate whether the number is non-zero (the "truthiness").
  2. Using safe navigation, which stops the traversal of the path if there's a null/undefined; note that the "!!" still works here because it gets the truthiness of null/undefined in the same way it would for a number (or string etc.).
  3. Using the getter in the template.
1
  • Thanks... this explains a lot !! Commented May 31, 2022 at 6:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .