Creating a Component Using Templates
This section demonstrates how to create a component using only the Template API.
This example creates a view that allows the user to enter their name and click a button.
Creating the Template File on the Client Side
The first step is to create the LitElement TypeScript template file on the client side in frontend/src/hello-world.ts.
This file contains the view structure.
Example: Creating the hello-world.ts TypeScript LitElement template file.
Source code
JavaScript
import { html, LitElement } from 'lit';
import '@vaadin/button';
import '@vaadin/text-field';
import '@axa-ch/input-text';
class HelloWorld extends LitElement {
render() {
return html`
<div>
<vaadin-text-field id="firstInput"></vaadin-text-field>
<axa-input-text id="secondInput"></axa-input-text>
<vaadin-button id="helloButton">Click me!</vaadin-button>
</div>
`;
}
}
customElements.define('hello-world', HelloWorld);-
This is the JavaScript ES6 module that defines a LitElement template.
-
The tag name should contain at least one dash (
-). For example,hello-worldis a valid tag name, buthelloworldisn’t. -
The imported dependencies are:
-
LitElement(from the LitElement library): this is the required superclass of all LitElement templates. -
vaadin-text-field,vaadin-buttonandaxa-input-textcomponents. -
htmlfor inline DOM templating.
-
Creating the Java Template Class
To use the client-side LitElement template on the server side, you need to create an associated Java class that extends the LitTemplate class.
Example: Creating the HelloWorld Java template class.
Source code
Java
@Tag("hello-world")
@NpmPackage(value = "@axa-ch/input-text", version = "4.3.11")
@JsModule("./src/hello-world.ts")
public class HelloWorld extends LitTemplate {
/**
* Creates the hello world template.
*/
public HelloWorld() {
}
}-
The
@Tagannotation name matches from the TypeScript template. This ensures that the tag name is the same on the server and the client. -
The
@JsModuleannotation binds the Java class to thehello-world.tstemplate class by specifying the relative path to the JavaScript module in thefrontendfolder in the project root. You can import multiple resources using the@JsModuleannotation, if needed. -
The
@NpmPackageannotation declares a dependency on theinput-textnpm package:@axa-ch/input-text 4.3.11. This annotation can be used to declare a dependency on any npm package.