Lightning Web Component - Render DOM Elements ConditionallyNot able to render dynamic Lightning Web...

How far did Gandalf and the Balrog drop from the bridge in Moria?

How would you translate this? バタコチーズライス

How do some PhD students get 10+ papers? Is that what I need for landing good faculty position?

Why is tert-butoxide often used in elimination reactions when it is not necessary?

Is there any way to stop a user from creating executables and running them?

Why won't the Republicans use a superdelegate system like the DNC in their nomination process?

What is the status of this patent?

Graphs for which a calculus student can reasonably compute the arclength

How to "add" units to results of pgfmathsetmacro?

Why aren't rainbows blurred-out into nothing after they are produced?

What is the farthest a camera can see?

Possible to ground-fault protect both legs of a MWBC with two single-pole breakers?

How can I see if the data in a SQL Server table is page-compressed?

Reimplementation of min() in Python

Case Condition for two lines

Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?

Why aren't rockets built with truss structures inside their fuel & oxidizer tanks to increase structural strength?

Are those flyers about apartment purchase a scam?

In which case does the Security misconfiguration vulnerability apply to?

Dogfights in outer space

What are those bumps on top of the Antonov-225?

Telephone number in spoken words

Are employers legally allowed to pay employees in goods and services equal to or greater than the minimum wage?

Beginner in need of a simple explanation of the difference between order of evaluation and precedence/associativity



Lightning Web Component - Render DOM Elements Conditionally


Not able to render dynamic Lightning Web ComponentCan't get refreshApex() to work in lwcUsing this.template.querySelectorAll() to modify the DOM in Lightning Web ComponentLightning web component slot is not working inside select?Assign content to multiple slots in LWC: how to insert the same slot content to multiple template slots in LWC?Design tokens doesn't work in LWC?Lightning Web component add an extra DOM elementUse equals in if conditions or expressionsWhy data- attribute sometimes doesn't work?Lightning Web Components - Custom Decorator support






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







1















I've started writing my first LWC component and I have a problem with conditionally rendering DOM elements. I want to render an element if an expression returns true and not just a property. According to the developer guide, this is not possible? I'm working with this guide: https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_conditional



Here is an example of what I'm trying to achieve:



<template for:each={hours} for:item="h">
<template if:true={h!==12}>
Work
</template>
<template if:true={h===12}>
Tea time
</template>
</template>


hours is an array containing primitives: 0 to 23. Each hour of the day is a "Work" hour except 12, which is "Tea time". This doesn't work. I tried passing a function too but that doesn't work as well. I can't even pass an expression such as hours[h]. The developer guide says I can pass a JS getter function but that won't help because I can't pass it a parameter.



How can I overcome this?



Thanks!










share|improve this question































    1















    I've started writing my first LWC component and I have a problem with conditionally rendering DOM elements. I want to render an element if an expression returns true and not just a property. According to the developer guide, this is not possible? I'm working with this guide: https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_conditional



    Here is an example of what I'm trying to achieve:



    <template for:each={hours} for:item="h">
    <template if:true={h!==12}>
    Work
    </template>
    <template if:true={h===12}>
    Tea time
    </template>
    </template>


    hours is an array containing primitives: 0 to 23. Each hour of the day is a "Work" hour except 12, which is "Tea time". This doesn't work. I tried passing a function too but that doesn't work as well. I can't even pass an expression such as hours[h]. The developer guide says I can pass a JS getter function but that won't help because I can't pass it a parameter.



    How can I overcome this?



    Thanks!










    share|improve this question



























      1












      1








      1








      I've started writing my first LWC component and I have a problem with conditionally rendering DOM elements. I want to render an element if an expression returns true and not just a property. According to the developer guide, this is not possible? I'm working with this guide: https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_conditional



      Here is an example of what I'm trying to achieve:



      <template for:each={hours} for:item="h">
      <template if:true={h!==12}>
      Work
      </template>
      <template if:true={h===12}>
      Tea time
      </template>
      </template>


      hours is an array containing primitives: 0 to 23. Each hour of the day is a "Work" hour except 12, which is "Tea time". This doesn't work. I tried passing a function too but that doesn't work as well. I can't even pass an expression such as hours[h]. The developer guide says I can pass a JS getter function but that won't help because I can't pass it a parameter.



      How can I overcome this?



      Thanks!










      share|improve this question














      I've started writing my first LWC component and I have a problem with conditionally rendering DOM elements. I want to render an element if an expression returns true and not just a property. According to the developer guide, this is not possible? I'm working with this guide: https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_conditional



      Here is an example of what I'm trying to achieve:



      <template for:each={hours} for:item="h">
      <template if:true={h!==12}>
      Work
      </template>
      <template if:true={h===12}>
      Tea time
      </template>
      </template>


      hours is an array containing primitives: 0 to 23. Each hour of the day is a "Work" hour except 12, which is "Tea time". This doesn't work. I tried passing a function too but that doesn't work as well. I can't even pass an expression such as hours[h]. The developer guide says I can pass a JS getter function but that won't help because I can't pass it a parameter.



      How can I overcome this?



      Thanks!







      lightning-web-components






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 22 hours ago









      ShaiShai

      1104 bronze badges




      1104 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          4















          1. You need array of objects.


          2. In each object, you can add a boolean which conveys the conditional rendering.



          Pls check below example:



          poc.html



          <template>
          <template for:each={hoursMain} for:item="h">
          <template if:false={h.isHour12}>
          <div key={h.hour} class="slds-theme_success">Work</div>
          </template>
          <template if:true={h.isHour12}>
          <div key={h.hour} class="slds-theme_error">Tea Time</div>
          </template>
          </template>
          </template>


          poc.js



          hours = [];
          @track hoursMain = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          // create new array for getting booleans
          this.hoursMain = this.hours.map(hr => {
          return {
          hour: hr,
          isHour12: (hr === 12)
          };
          });
          }


          isHour12 will give you the required boolean inside iteration in HTML





          This actually is better with components



          In this case you can use getters and also the code will be clean, maintainable and scalable



          parent.html:



          <template>
          <template for:each={hours} for:item="h">
          <div key={h.hour}>
          <c-child hour={h}></c-child>
          </div>
          </template>
          </template>


          parent.js:



          @track hours = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          }


          child.html:



          <template>
          <template if:false={isHour12}>
          <div class="slds-theme_success">Work</div>
          </template>
          <template if:true={isHour12}>
          <div class="slds-theme_error">Tea Time</div>
          </template>
          </template>


          child.js:



          export default class Child extends LightningElement {
          @api hour;
          get isHour12() {
          return this.hour === 12;
          }
          }





          share|improve this answer




























          • This will work but it's such a weird way to do it. It will increase memory consumption but what I'm more afraid of is the data management. My example here was really simple but in real life, I'll have to keep that boolean array updated on every data change occurring on the app, bummer :-

            – Shai
            22 hours ago











          • added better approach in that case in answer

            – salesforce-sas
            22 hours ago



















          0














          You can either add an property like "isTeaTime" in your data and use that or you can create a child-row component (with respective public property for the current data row) or similiar as iteration item which will take over the logic for rendering






          share|improve this answer


























          • Thanks for the detailed example. It's basically breaking it to components. In other popular JS frameworks the solution is so much easier to develop :- hope they will add more options on future releases.

            – Shai
            21 hours ago
















          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "459"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f273377%2flightning-web-component-render-dom-elements-conditionally%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4















          1. You need array of objects.


          2. In each object, you can add a boolean which conveys the conditional rendering.



          Pls check below example:



          poc.html



          <template>
          <template for:each={hoursMain} for:item="h">
          <template if:false={h.isHour12}>
          <div key={h.hour} class="slds-theme_success">Work</div>
          </template>
          <template if:true={h.isHour12}>
          <div key={h.hour} class="slds-theme_error">Tea Time</div>
          </template>
          </template>
          </template>


          poc.js



          hours = [];
          @track hoursMain = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          // create new array for getting booleans
          this.hoursMain = this.hours.map(hr => {
          return {
          hour: hr,
          isHour12: (hr === 12)
          };
          });
          }


          isHour12 will give you the required boolean inside iteration in HTML





          This actually is better with components



          In this case you can use getters and also the code will be clean, maintainable and scalable



          parent.html:



          <template>
          <template for:each={hours} for:item="h">
          <div key={h.hour}>
          <c-child hour={h}></c-child>
          </div>
          </template>
          </template>


          parent.js:



          @track hours = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          }


          child.html:



          <template>
          <template if:false={isHour12}>
          <div class="slds-theme_success">Work</div>
          </template>
          <template if:true={isHour12}>
          <div class="slds-theme_error">Tea Time</div>
          </template>
          </template>


          child.js:



          export default class Child extends LightningElement {
          @api hour;
          get isHour12() {
          return this.hour === 12;
          }
          }





          share|improve this answer




























          • This will work but it's such a weird way to do it. It will increase memory consumption but what I'm more afraid of is the data management. My example here was really simple but in real life, I'll have to keep that boolean array updated on every data change occurring on the app, bummer :-

            – Shai
            22 hours ago











          • added better approach in that case in answer

            – salesforce-sas
            22 hours ago
















          4















          1. You need array of objects.


          2. In each object, you can add a boolean which conveys the conditional rendering.



          Pls check below example:



          poc.html



          <template>
          <template for:each={hoursMain} for:item="h">
          <template if:false={h.isHour12}>
          <div key={h.hour} class="slds-theme_success">Work</div>
          </template>
          <template if:true={h.isHour12}>
          <div key={h.hour} class="slds-theme_error">Tea Time</div>
          </template>
          </template>
          </template>


          poc.js



          hours = [];
          @track hoursMain = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          // create new array for getting booleans
          this.hoursMain = this.hours.map(hr => {
          return {
          hour: hr,
          isHour12: (hr === 12)
          };
          });
          }


          isHour12 will give you the required boolean inside iteration in HTML





          This actually is better with components



          In this case you can use getters and also the code will be clean, maintainable and scalable



          parent.html:



          <template>
          <template for:each={hours} for:item="h">
          <div key={h.hour}>
          <c-child hour={h}></c-child>
          </div>
          </template>
          </template>


          parent.js:



          @track hours = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          }


          child.html:



          <template>
          <template if:false={isHour12}>
          <div class="slds-theme_success">Work</div>
          </template>
          <template if:true={isHour12}>
          <div class="slds-theme_error">Tea Time</div>
          </template>
          </template>


          child.js:



          export default class Child extends LightningElement {
          @api hour;
          get isHour12() {
          return this.hour === 12;
          }
          }





          share|improve this answer




























          • This will work but it's such a weird way to do it. It will increase memory consumption but what I'm more afraid of is the data management. My example here was really simple but in real life, I'll have to keep that boolean array updated on every data change occurring on the app, bummer :-

            – Shai
            22 hours ago











          • added better approach in that case in answer

            – salesforce-sas
            22 hours ago














          4












          4








          4








          1. You need array of objects.


          2. In each object, you can add a boolean which conveys the conditional rendering.



          Pls check below example:



          poc.html



          <template>
          <template for:each={hoursMain} for:item="h">
          <template if:false={h.isHour12}>
          <div key={h.hour} class="slds-theme_success">Work</div>
          </template>
          <template if:true={h.isHour12}>
          <div key={h.hour} class="slds-theme_error">Tea Time</div>
          </template>
          </template>
          </template>


          poc.js



          hours = [];
          @track hoursMain = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          // create new array for getting booleans
          this.hoursMain = this.hours.map(hr => {
          return {
          hour: hr,
          isHour12: (hr === 12)
          };
          });
          }


          isHour12 will give you the required boolean inside iteration in HTML





          This actually is better with components



          In this case you can use getters and also the code will be clean, maintainable and scalable



          parent.html:



          <template>
          <template for:each={hours} for:item="h">
          <div key={h.hour}>
          <c-child hour={h}></c-child>
          </div>
          </template>
          </template>


          parent.js:



          @track hours = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          }


          child.html:



          <template>
          <template if:false={isHour12}>
          <div class="slds-theme_success">Work</div>
          </template>
          <template if:true={isHour12}>
          <div class="slds-theme_error">Tea Time</div>
          </template>
          </template>


          child.js:



          export default class Child extends LightningElement {
          @api hour;
          get isHour12() {
          return this.hour === 12;
          }
          }





          share|improve this answer
















          1. You need array of objects.


          2. In each object, you can add a boolean which conveys the conditional rendering.



          Pls check below example:



          poc.html



          <template>
          <template for:each={hoursMain} for:item="h">
          <template if:false={h.isHour12}>
          <div key={h.hour} class="slds-theme_success">Work</div>
          </template>
          <template if:true={h.isHour12}>
          <div key={h.hour} class="slds-theme_error">Tea Time</div>
          </template>
          </template>
          </template>


          poc.js



          hours = [];
          @track hoursMain = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          // create new array for getting booleans
          this.hoursMain = this.hours.map(hr => {
          return {
          hour: hr,
          isHour12: (hr === 12)
          };
          });
          }


          isHour12 will give you the required boolean inside iteration in HTML





          This actually is better with components



          In this case you can use getters and also the code will be clean, maintainable and scalable



          parent.html:



          <template>
          <template for:each={hours} for:item="h">
          <div key={h.hour}>
          <c-child hour={h}></c-child>
          </div>
          </template>
          </template>


          parent.js:



          @track hours = [];
          connectedCallback() {
          for (let i = 0; i < 24; i++) this.hours.push(i);
          }


          child.html:



          <template>
          <template if:false={isHour12}>
          <div class="slds-theme_success">Work</div>
          </template>
          <template if:true={isHour12}>
          <div class="slds-theme_error">Tea Time</div>
          </template>
          </template>


          child.js:



          export default class Child extends LightningElement {
          @api hour;
          get isHour12() {
          return this.hour === 12;
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 22 hours ago

























          answered 22 hours ago









          salesforce-sassalesforce-sas

          4,8981 gold badge2 silver badges23 bronze badges




          4,8981 gold badge2 silver badges23 bronze badges
















          • This will work but it's such a weird way to do it. It will increase memory consumption but what I'm more afraid of is the data management. My example here was really simple but in real life, I'll have to keep that boolean array updated on every data change occurring on the app, bummer :-

            – Shai
            22 hours ago











          • added better approach in that case in answer

            – salesforce-sas
            22 hours ago



















          • This will work but it's such a weird way to do it. It will increase memory consumption but what I'm more afraid of is the data management. My example here was really simple but in real life, I'll have to keep that boolean array updated on every data change occurring on the app, bummer :-

            – Shai
            22 hours ago











          • added better approach in that case in answer

            – salesforce-sas
            22 hours ago

















          This will work but it's such a weird way to do it. It will increase memory consumption but what I'm more afraid of is the data management. My example here was really simple but in real life, I'll have to keep that boolean array updated on every data change occurring on the app, bummer :-

          – Shai
          22 hours ago





          This will work but it's such a weird way to do it. It will increase memory consumption but what I'm more afraid of is the data management. My example here was really simple but in real life, I'll have to keep that boolean array updated on every data change occurring on the app, bummer :-

          – Shai
          22 hours ago













          added better approach in that case in answer

          – salesforce-sas
          22 hours ago





          added better approach in that case in answer

          – salesforce-sas
          22 hours ago













          0














          You can either add an property like "isTeaTime" in your data and use that or you can create a child-row component (with respective public property for the current data row) or similiar as iteration item which will take over the logic for rendering






          share|improve this answer


























          • Thanks for the detailed example. It's basically breaking it to components. In other popular JS frameworks the solution is so much easier to develop :- hope they will add more options on future releases.

            – Shai
            21 hours ago


















          0














          You can either add an property like "isTeaTime" in your data and use that or you can create a child-row component (with respective public property for the current data row) or similiar as iteration item which will take over the logic for rendering






          share|improve this answer


























          • Thanks for the detailed example. It's basically breaking it to components. In other popular JS frameworks the solution is so much easier to develop :- hope they will add more options on future releases.

            – Shai
            21 hours ago
















          0












          0








          0







          You can either add an property like "isTeaTime" in your data and use that or you can create a child-row component (with respective public property for the current data row) or similiar as iteration item which will take over the logic for rendering






          share|improve this answer













          You can either add an property like "isTeaTime" in your data and use that or you can create a child-row component (with respective public property for the current data row) or similiar as iteration item which will take over the logic for rendering







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 22 hours ago









          Renji-xDRenji-xD

          1,8162 silver badges5 bronze badges




          1,8162 silver badges5 bronze badges
















          • Thanks for the detailed example. It's basically breaking it to components. In other popular JS frameworks the solution is so much easier to develop :- hope they will add more options on future releases.

            – Shai
            21 hours ago





















          • Thanks for the detailed example. It's basically breaking it to components. In other popular JS frameworks the solution is so much easier to develop :- hope they will add more options on future releases.

            – Shai
            21 hours ago



















          Thanks for the detailed example. It's basically breaking it to components. In other popular JS frameworks the solution is so much easier to develop :- hope they will add more options on future releases.

          – Shai
          21 hours ago







          Thanks for the detailed example. It's basically breaking it to components. In other popular JS frameworks the solution is so much easier to develop :- hope they will add more options on future releases.

          – Shai
          21 hours ago




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Salesforce Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f273377%2flightning-web-component-render-dom-elements-conditionally%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

          Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

          Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...