HTML
<template>
<lightning-card title="Contact List">
<div class="slds-m-around_medium">
<template if:true={contacts}>
<ul class="slds-list_vertical">
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template if:false={contacts}>
<p>No contacts found.</p>
</template>
</div>
</lightning-card>
</template>
Js
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactLWCController.getContacts';
export default class ContactList extends LightningElement {
contacts;
@wire(getContacts)
wiredContacts({ error, data }) {
if (data) {
this.contacts = data;
} else if (error) {
console.error('Error fetching contacts:', error);
}
}
}
Controller
public with sharing class ContactLWCController {
//@AuraEnabled annotation marks the Apex method as accessible to Lightning components (LWC, Aura components).
@AuraEnabled(cacheable=true)
public static List getContacts() {
return [SELECT Id, Name FROM Contact LIMIT 10];
}
}