Example: Handle User Input with Complex Expressions

This component has an input field that asks for a name to greet. When the value of the input field changes, the component changes the value of the bound name property and uses complex expressions to format the output.

1<template>
2  <input value="{name}" oninput="{handleInput}" placeholder="Enter your name" />
3  <div>{name ? `Hello, ${name.trim().toUpperCase()}!` : 'Please enter your name'}</div>
4  <div>{name ? `Your name has ${name.length} characters` : ''}</div>
5</template>
1import { LightningElement } from "lwc";
2
3export default class UserInputComponent extends LightningElement {
4  name = "";
5
6  handleInput(event) {
7    this.name = event.target.value;
8  }
9}

The <input> element uses the oninput event to listen for a change to its value. To bind the handleInput function to the template, we use the same syntax that we use to bind a property, {...}. The handleInput JavaScript function executes when the value of the <input> element changes.

When the value of the name property changes, the component re-renders and the following expression is evaluated.

1{name ? `Hello, ${name.toUpperCase()}!` : 'Please enter your name'}

Notice in the JavaScript class that handleInput is passed an event object. The event object contains information about the input event. The component uses the event object to get the value that the user enters into the input field.

Release Preview

This release is in preview. Features described here don't become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can't guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.