Sub topic 2
Cards, Icons, Buttons, and Forms
This chapter assumes basic HTML, CSS, modern JavaScript, and the standard LWC structure: an HTML template, JavaScript class, and optional CSS file.
Cards, icons, and buttons
Lightning base components are reusable lightning-* elements with built-in behavior, styling, and accessibility support. A lightning-card provides a standard container. Place an action in its actions slot.
<template>
<lightning-card title="Contact search" icon-name="standard:contact">
<lightning-button
slot="actions"
label="Clear"
onclick={handleClear}
></lightning-button>
<div class="slds-var-p-around_medium">
<lightning-icon
icon-name="utility:search"
alternative-text="Search"
size="small"
></lightning-icon>
<lightning-input
type="search"
label="Name"
value={searchKey}
onchange={handleChange}
></lightning-input>
</div>
</lightning-card>
</template>lightning-icon displays a Salesforce icon. Always provide alternative-text unless the icon is purely decorative. A lightning-button exposes a standard button and sends an event when clicked.
Collecting input with `lightning-input`
lightning-input supports types such as text, search, email, number, and checkbox. Its label identifies the field for users and assistive technology. The value attribute displays a JavaScript property.
import { LightningElement } from 'lwc';
export default class ContactSearch extends LightningElement {
searchKey = '';
handleChange(event) {
this.searchKey = event.target.value;
}
handleClear() {
this.searchKey = '';
}
}The template reads {searchKey}. The controller updates that property when the input dispatches its change event.
Handling events and passing data
An event is a message about something that happened. The onclick and onchange attributes connect template events to JavaScript methods. Read the changed value from event.target.value. For custom child components, pass data with public properties and communicate upward with custom events.
Record forms with `lightning-record-edit-form`
Use lightning-record-edit-form to create or edit Salesforce records through Lightning Data Service. lightning-input-field renders fields using the object’s metadata, including labels and validation.
<template>
<lightning-record-edit-form
object-api-name="Contact"
onsuccess={handleSuccess}
>
<lightning-messages></lightning-messages>
<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-button
type="submit"
variant="brand"
label="Save"
></lightning-button>
</lightning-record-edit-form>
</template>The button submits because its type is submit. lightning-messages displays server and validation errors.
Exercise
Which attribute makes the Save button submit the record form?
Show answer
type="submit".