Creating an In-project Web Component

In the majority of circumstances, the best way to integrate a public Web Component into Vaadin, is to follow the steps in Integrating a Web component.

As an alternative, if you want to create a UI component that is specific to your application, you can integrate and develop the component within your application project.

In this section, we demonstrate how to do this using the Vaadin Base Starter.

Creating the Polymer 3 Component Template

The first step is to create the JavaScript Polymer 3 template in frontend/my-test-element/my-test-element.js

Example: Defining the my-test-element JavaScript template.

js

  1. import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
  2. class MyTestElement extends PolymerElement {
  3. static get template() {
  4. return html`
  5. <h2>Hello</h2>
  6. `;
  7. }
  8. }
  9. window.customElements.define('my-test-element', MyTestElement);

Creating the Component Java API

This works in exactly the same way as described in Creating Java API for a Web Component, except that the static files are loaded from your project. You can easily modify them while creating the Java API.

Example: Defining the matching template class.

Java

  1. @Tag("my-test-element")
  2. @JsModule("my-test-element/my-test-element.js")
  3. public class MyTest extends Component {
  4. public MyTest(String prop1) {
  5. getElement().setProperty("prop1", prop1);
  6. }
  7. }

Using the Web Component

You can now use the component in other parts of your code.

Example: Using the component in the MainView class.

Java

  1. public class MainView extends VerticalLayout {
  2. public MainView() {
  3. add(new MyTest("World"));
  4. }
  5. }