0
<template  for:each={listA} for:item="a">
    <template  for:each={listB} for:item="b">
        <td data-id={a+b}>
        </td>
</template>  
</template>

How can I get my concatenated value using a get method (eg a+b). Even I tried using a get method but it doesn't seem to work. Can someone help me here?

2
  • I did take a look at that but here I would need to get both the for:each's values onto my data-id.
    – Harry
    Oct 27, 2021 at 6:49
  • 1
    @Harry welcome to SFSE. The other Q&A clearly covers that expressions are not supported (beyond simple property access) and that you must therefore ensure that you engineer the properties on your LWC to pre-compute the desired values so they can be exposed simply, with no need for a complex expression, in your template.
    – Phil W
    Oct 27, 2021 at 7:59

1 Answer 1

0

There is no way to use formulas on a LWC expression. To achieve that, you need to create a new list in your JavaScript which contains all the values that you want to use. In your case scenario, just create a new list that contains the addition of values on listA and listB. Then iterate that and use the values that you calculated in JavaScript. You have an example of a calculation in the following component:

JS:

import { LightningElement } from "lwc";

export default class MyComponent extends LightningElement {
  listA = [
    { value: 5, name: "Foo" },
    { value: 10, name: "John" }
  ];
  listB = [
    { anotherValue: 3, name: "Doe" },
    { anotherValue: 15, name: "Fighters" }
  ];

  get myNewList() {
    if (this.listA && this.listB) {
      let myCalculatedList = [];

      this.listA.forEach((elementOfListA) => {
        this.listB.forEach((elementOfListB) => {
          myCalculatedList.push({
            calculatedNumber:
              elementOfListA.value + elementOfListB.anotherValue,
            calculatedString: `${elementOfListA.name} ${elementOfListB.name}`
          });
        });
      });
      return myCalculatedList;
    }
    return [];
  }
}

HTML:

<template>
  <ul>
    <template for:each={myNewList} for:item="newListElement">
      <li key={newListElement.calculatedString}>
        {newListElement.calculatedNumber} - {newListElement.calculatedString}
      </li>
    </template>
  </ul>
</template>
2
  • unfortunately my ListA and ListB are dynamic so am afraid that I will not be able to add anything on my actualy records from the database.
    – Harry
    Oct 27, 2021 at 8:09
  • Hi Harry. I've updated my answer by putting an example. Doesn't really matter if the list is dynamic (in this case, obviously, you need to know the properties of the elements in the lists that you are going to use), whenever the value for listA or listB is changed, because of LWC Reactivity, the property myNewList is recalculated and the component is re-rendered. This should cover your case scenario. Oct 27, 2021 at 18:02

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