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: a custom `lit-html` directive #10

Open vlukashov opened 5 years ago

vlukashov commented 5 years ago

This approach to reactive form rendering depends on the lit-html library. Vaadin Form comes with a set of custom directives for lit-html that allow linking DOM elements to a form instance and using the form properties in the template.

import { VaadinForm } from '@vaadin/form';
import { html } from 'lit-html';

const form = new VaadinForm();

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

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

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