Sub topic 1
The Web Component Standards LWC Builds On
Prerequisites
Assume you know basic HTML, CSS, JavaScript classes, and browser events. You should also understand that a UI component combines markup, behavior, and styles.
The Web Component Standards LWC Builds On
Web components are browser standards for creating reusable HTML elements. They combine four related features:
- Custom elements let you define new HTML tags.
- Shadow DOM isolates a component's internal markup and styles.
- HTML templates and slots support reusable markup and content insertion.
- ES modules organize JavaScript into importable files.
LWC uses these standards, then adds Salesforce integration, a compiler, templates, decorators, and framework conventions.
Custom Elements: Defining Your Own HTML Tags
A custom element is an HTML element with a developer-defined name. Its name must contain a hyphen, such as hello-greeting. A JavaScript class defines its behavior, and customElements.define() registers the tag.
class HelloGreeting extends HTMLElement {
connectedCallback() {
this.textContent = `Hello, ${this.getAttribute('name') ?? 'World'}!`;
}
}
customElements.define('hello-greeting', HelloGreeting);After registration, the browser understands <hello-greeting name="Ada"></hello-greeting> and calls connectedCallback() when the element enters the document.
Shadow DOM: Encapsulating Markup and Styles
Shadow DOM creates a private DOM tree attached to an element. Its markup and CSS do not normally interfere with the page around it. This reduces naming conflicts and makes a component easier to reuse.
LWC commonly renders component templates inside a shadow boundary. The exact rendering strategy can vary by platform and configuration, so treat the boundary as an encapsulation contract rather than relying on internal DOM details.
Templates and Slots in the Platform
The <template> element stores markup that is inert until code uses it. A <slot> is a placeholder where a component can display content supplied by its parent. These standards support composition without requiring parent code to know a child's internal structure.
ES Modules as the Unit of Code Sharing
An ES module is a JavaScript file with explicit export and import statements. Modules keep dependencies clear and avoid placing every variable in the global scope. An LWC JavaScript file is an ES module that imports LightningElement and exports one component class.
What Lightning Web Components Are
An LWC component is usually a bundle containing an HTML template, a JavaScript class, optional CSS, and metadata. The class extends LightningElement; the framework connects it to a custom element and manages rendering. LWC template expressions, reactivity, decorators such as @api, and lifecycle hooks are framework additions built on browser standards.
Exercise
Which feature isolates a component's internal markup and styles?
Show answer
Shadow DOM.