Sub topic 2
How the Template and Class Work Together
Assume you know basic HTML, JavaScript classes, ES modules, and CSS selectors. In a Lightning web component (LWC), the HTML template describes the visible structure. The JavaScript class stores data and handles behavior. The framework connects them through the component instance.
How the Template and Class Work Together
The template can read fields from the class with expressions such as {name}. The @api decorator makes a property public, so a parent component or App Builder can set it.
<template>
<lightning-card title="Greeting">
<p class="greeting">Hello, {name}!</p>
</lightning-card>
</template>import { LightningElement, api } from 'lwc';
export default class GreetingCard extends LightningElement {
@api name = 'World';
}When a parent changes name, LWC rerenders the expression in the template. The HTML file must contain one root template element. The JavaScript class must use the same base name as the bundle folder.
The CSS File and Style Scoping
A same-named CSS file styles the component's own template. LWC scopes its selectors so that a class such as greeting does not accidentally style matching elements elsewhere on the page.
.greeting {
color: #032d60;
font-weight: bold;
}A component stylesheet can style elements in its template, but it should not depend on reaching into a child component's internal markup. Use public properties, slots, or supported styling APIs when a child needs configuration.
The Configuration File
The metadata file must be named greetingCard.js-meta.xml and must sit beside the HTML, JavaScript, and CSS files. It controls deployment metadata, whether the component appears in builders, and where it can be placed.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Greeting Card</masterLabel>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>| Element | Purpose |
|---|---|
| apiVersion | Selects the Salesforce API behavior |
| isExposed | Makes the component available to builders |
| targets | Lists the page types that can contain it |
A component can work without CSS, but a deployed component still needs correctly named HTML, JavaScript, and metadata files.
Exercise
What happens when a parent sets the public name property to "Ada"?
Show answer
The class receives the new value, and LWC rerenders the template expression as "Hello, Ada!".