vaadin / proposal-for-vaadin-form

Small and fast framework-agnostic library for creating forms with Web Components
Apache License 2.0
9 stars 0 forks source link

Form rendering: `LitElement` integration #9

Open vlukashov opened 5 years ago

vlukashov commented 5 years ago

This approach to reactive form rendering depends on the lit-element library. Vaadin Forms taps into the LitElement's change detection mechanism and calls the renderer() method on any form property change.

import { LitElement, customElement, html } from 'lit-element';
import { VaadinForm, form } from '@vaadin/form';

@customElement('field-validation')
class MyComponent extends LitElement {

  @form() form = new VaadinForm();

  render() {
    return html`
      <!-- well-known form inputs just work -->
      <div class="form-field">
        <label>User Name <input type="text" .value=${form.username}></label>
        ${form.username.touched && form.username.invalid
          ? html`<p class="error">${form.username.message}</p>`
          : ''}
      </div>

      <!-- arbitrary form inputs need explicit bindings between
          the DOM and the Vaadin Form's field instance -->
      <div class="form-field">
        <x-custom-form-field
          name="customProp"
          .value=${form.customProp.value}
          @input=${form.customProp.onInput}
          @change=${form.customProp.onChange}
          @blur=${form.customProp.onBlur}
          @focus=${form.customProp.onFocus}
        ></x-custom-form-field>
      </div>

      <button @click=${form.submit} ?disabled=${!form.canSubmit}>
        Submit
      </button>
    `;
  }
}