Skip to content

Instantly share code, notes, and snippets.

@cyberjus
Created December 27, 2018 16:04
Show Gist options
  • Save cyberjus/b54d7c2b288549e9dfb8fd4adde4b6c6 to your computer and use it in GitHub Desktop.
Save cyberjus/b54d7c2b288549e9dfb8fd4adde4b6c6 to your computer and use it in GitHub Desktop.
LWC Object Array
.classy {
background-color: pink;
}
<template>
<h2>Hello World</h2>
<ul>
<template for:each={theList} for:item="listItem">
<li key={listItem.id} class={listItem.styleClass}>
{listItem.label}
</li>
</template>
</ul>
<button onclick={clickButton}>Style List</button>
</template>
import { LightningElement, track } from 'lwc';
import getList from '@salesforce/apex/Test.getList';
export default class HelloWorld extends LightningElement {
// Works as Expected
/*@track theList = [
{ id: 1, label: "Item 1" },
{ id: 2, label: "Item 2" },
{ id: 3, label: "Item 3" }
]*/
// Does not work
@track theList;
connectedCallback() {
console.log('load');
getList()
.then(result => {
console.log(JSON.stringify(result));
this.theList = result;
});
}
clickButton(event) {
console.log("click button");
for (let i=0; i<this.theList.length; i++) {
console.log(i);
this.theList[i].styleClass = "classy";
}
}
}
public with sharing class Test {
@AuraEnabled(cacheable=true)
public static TestObj[] getList() {
TestObj[] tests = new TestObj[]{
new TestObj('1', 'Item 1'),
new TestObj('2', 'Item 2'),
new TestObj('3', 'Item 3')
};
return tests;
}
public class TestObj {
@AuraEnabled public String id;
@AuraEnabled public String label;
@AuraEnabled public String styleClass {get; set;}
public TestObj(String id, String label) {
this.id = id;
this.label = label;
this.styleClass = '';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment