Extending Components

You can create a new component by extending any existing component.

For most components, there is a client-side component and a corresponding server-side component:

  • Client-side component: Contains the HTML, CSS, and JavaScript, and defines a set of properties that determine the behavior of the component on the client side.

  • Server-side component: Contains Java code that allows for changing of the client-side properties, and manages the component behavior on the server side.

You can extend a component on either the server or client side. Note that these are alternative approaches that are mutually exclusive.

In this section we demonstrate the two different approaches to achieve the same changes to the prebuilt text field component.

Extending a Component Using the Server-side Approach

Extending a server-side component is useful when you want to add new functionality (as opposed to visual aspects) to an existing component. Suitable examples include automatically processing data, adding default validators, and combining multiple simple components into a field that manages complex data.

Tip
If your component contains a lot of logic that could easily be done on the client side, consider implementing it as a Web Component and creating a wrapper for it. This approach may offer a better user experience and result in less load on the server.

In this example, we create a NumericField component by extending the TextField component. The new component contains a default number that the user can change using + and - controls.

vaadin-numeric-field

Example: Creating a NumericField component by extending the TextField component.

Java

  1. @CssImport("./styles/numeric-field-styles.css")
  2. public class NumericField extends TextField {
  3. private Button substractBtn;
  4. private Button addBtn;
  5. private static final int DEFAULT_VALUE = 0;
  6. private static final int DEFAULT_INCREMENT = 1;
  7. private int numericValue;
  8. private int incrementValue;
  9. private int decrementValue;
  10. public NumericField() {
  11. this(DEFAULT_VALUE, DEFAULT_INCREMENT,
  12. -DEFAULT_INCREMENT);
  13. }
  14. public NumericField(int value, int incrementValue,
  15. int decrementValue) {
  16. setNumericValue(value);
  17. this.incrementValue = incrementValue;
  18. this.decrementValue = decrementValue;
  19. setPattern("-?[0-9]*");
  20. setPreventInvalidInput(true);
  21. addChangeListener(event -> {
  22. String text = event.getSource().getValue();
  23. if (StringUtils.isNumeric(text)) {
  24. setNumericValue(Integer.parseInt(text));
  25. } else {
  26. setNumericValue(DEFAULT_VALUE);
  27. }
  28. });
  29. substractBtn = new Button("-", event -> {
  30. setNumericValue(numericValue +
  31. decrementValue);
  32. });
  33. addBtn = new Button("+", event -> {
  34. setNumericValue(numericValue +
  35. incrementValue);
  36. });
  37. getElement().setAttribute("theme", "numeric");
  38. styleBtns();
  39. addToPrefix(substractBtn);
  40. addToSuffix(addBtn);
  41. }
  42. private void styleBtns() {
  43. // Note: The same as addThemeVariants
  44. substractBtn.getElement()
  45. .setAttribute("theme", "icon");
  46. addBtn.getElement()
  47. .setAttribute("theme", "icon");
  48. }
  49. public void setNumericValue(int value) {
  50. numericValue = value;
  51. setValue(value + "");
  52. }
  53. // getters and setters
  54. }

As an alternative, you can extend the Composite class that has a minimal API. This hides methods available in the more extensive API that is exposed when your custom components extends an implementation of Component.

Note
The Element API contains methods to update and query various parts of the element, such as the attributes. Every component has a getElement() method that allows you to to access it. See Creating a Component Using Multiple Elements for more.

We import additional styles for the component using the @CssImport annotation. These styles apply only to our NumericField component, and not to all TextField components.

Example: Creating numeric-field-styles.css to customize the appearance of the vaadin-text-field component.

styles/numeric-field-styles.css

  1. :host([theme~="numeric"]) [part="input-field"] {
  2. background-color: var(--lumo-base-color);
  3. border: 1px solid var(--lumo-contrast-30pct);
  4. box-sizing: border-box;
  5. }
  6. :host([theme~="numeric"]) [part="value"]{
  7. text-align: center;
  8. }

See Styling Components for more information.

Extending a Component Using the Client-side Approach

Vaadin client-side components are based on Polymer 3 that supports extending existing components. You can use the extends property to extend existing Polymer elements.

There are five ways to inherit a template from another Polymer element:

  1. Inheriting a base class template without modifying it.

  2. Overriding a base class template in a child class.

  3. Modifying a copy of a superclass template.

  4. Extending a base class template in a child class.

  5. Providing template-extension points in a base class for content from a child class.

Extending by Modifying a Copy of a Superclass Template

In this example, we demonstrate how to create a new component by modifying a copy of a superclass template. We build a NumberFieldElement by extending Vaadin.TextFieldElement. The new component contains a default number that the user can change using + and - controls.

vaadin-number-field

It is important to remember that when a component template is extended, the properties and methods of the parent template become available to the child template.

Note
By default, a child component uses the template of the parent component, unless the child component provides its own template by overriding the static getter method template. The parent’s template is accessed using super.template.

Next, specify the element from which the child component inherits. In this case we specify that NumberFieldElement inherits (including the properties and methods) from Vaadin.TextFieldElement:

js

  1. import {html} from
  2. '@polymer/polymer/lib/utils/html-tag.js';
  3. import {TextFieldElement} from
  4. '@vaadin/vaadin-text-field/src/vaadin-text-field.js';
  5. let memoizedTemplate;
  6. class NumberFieldElement extends TextFieldElement {
  7. static get template() {
  8. if (!memoizedTemplate) {
  9. const superTemplate = super.template
  10. .cloneNode(true);
  11. const inputField = superTemplate.content
  12. .querySelector('[part="input-field"]');
  13. const prefixSlot = superTemplate.content
  14. .querySelector('[name="prefix"]');
  15. const decreaseButton = html`<div
  16. part="decrease-button"
  17. on-click="_decreaseValue"></div>`;
  18. const increaseButton = html`<div
  19. part="increase-button"
  20. on-click="_increaseValue"></div>`;
  21. inputField.insertBefore(
  22. decreaseButton.content, prefixSlot);
  23. inputField.appendChild(
  24. increaseButton.content);
  25. memoizedTemplate = html`<style>
  26. [part="decrease-button"]::before {
  27. content: "−";
  28. }
  29. [part="increase-button"]::before {
  30. content: "+";
  31. }
  32. </style>
  33. ${superTemplate}`;
  34. }
  35. return memoizedTemplate;
  36. }
  37. static get is() {
  38. return 'vaadin-number-field';
  39. }
  40. static get properties() {
  41. return {
  42. decrementValue: {
  43. type: Number,
  44. value: -1,
  45. reflectToAttribue: true,
  46. observer: '_decrementChanged'
  47. },
  48. incrementValue: {
  49. type: Number,
  50. value: 1,
  51. reflectToAttribue: true,
  52. observer: '_incrementChanged'
  53. }
  54. // Note: the value is stored in the
  55. // TF's value property.
  56. };
  57. }
  58. _decreaseValue() {
  59. this.__add(this.decrementValue);
  60. }
  61. _increaseValue() {
  62. this.__add(this.incrementValue);
  63. }
  64. __add(value) {
  65. this.value = parseInt(this.value, 10) + value;
  66. this.dispatchEvent(
  67. new CustomEvent('change', {bubbles: true}));
  68. }
  69. _valueChanged(newVal, oldVal) {
  70. this.value = this.focusElement.value;
  71. super._valueChanged(this.value, oldVal);
  72. }
  73. /* ... */
  74. }

To modify the template we override the template static getter. Note that the expression ${super.template} inserts the base class template into the newly constructed template. The newly constructed template is memoized for further invocations of template.

See Inherit a template from another Polymer element in the Polymer documentation for more.