I'm trying to output a list of strings separated by commas in LWC, such as:
cat, dog, mouse
I need to use template for:each and output a list item and a comma, but only if the item is not the last in the list. But I'm having trouble since LWC does not support comparison operations in templates. I tried to set a field in JS to indicate which element is the last:
HTML:
<template for:each={animals.data} for:item="animal">
<b key={animal.Id}>{animal.Name}</b>
<template if:false={animal.isLast}>
,
</template>
</template>
JS:
@wire(getAnimals)
assignAnimals(animals) {
this.animals = animals;
if (this.animals.data && this.animals.data.length > 0) {
this.animals.data[this.animals.data.length - 1].isLast = true;
}
}
But I cannot assign to this.animals.data[this.animals.data.length - 1].isLast because JS Proxy is guarding it.
TypeError: "proxy set handler returned false for property '"isLast"'"
The other options would be to create isLast field in the controller, but I would need to create a wrapper class. Another possibility would be some CSS tricks, but I don't want to do that.
Is there any simple way to do this?