Created
February 4, 2023 00:14
-
-
Save soelen/5a34780ee9f1c260076f319e2631f9b9 to your computer and use it in GitHub Desktop.
Form Participation - Required
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { css, html, LitElement, TemplateResult } from 'lit'; | |
import { customElement, property, query } from 'lit/decorators.js'; | |
import { live } from 'lit/directives/live.js'; | |
import { FormControlMixin, requiredValidator } from '@open-wc/form-control'; | |
@customElement( 'an-input' ) | |
export class AnInput extends FormControlMixin(LitElement) { | |
static formControlValidator = [requiredValidator]; | |
static styles = css` | |
/** Custom styles here potentially for a design system */ | |
`; | |
@property({ type: Boolean, reflect: true }) required = false; | |
@property() value = ''; | |
@property() validationMessage = ''; | |
@query('input') validationTarget: HTMLInputElement | null | undefined; | |
render(): TemplateResult { | |
return html` | |
<label for="input"><slot></slot></label> | |
<input | |
aria-describedby="helper-text" | |
id="input" | |
type="text" | |
.required="${live(this.required)}" | |
.value="${live(this.value)}" | |
@input="${this._onChange}" | |
> | |
<span id="helper-text">${this.validationMessage}</span>`; | |
} | |
validationMessageCallback(message: string): void { | |
this.validationMessage = message; | |
} | |
updated(changedProperties: Map<string, unknown>): void { | |
if (changedProperties.has('value')) { | |
this.setValue(this.value); | |
} | |
} | |
private _onChange(event: Event & { target: HTMLInputElement}): void { | |
this.value = event.target.value; | |
} | |
} | |
declare global { | |
interface HTMLElementTagNameMap { | |
'an-input': AnInput, | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { LitElement, css, html } from 'lit' | |
import { customElement, property } from 'lit/decorators.js' | |
import './an-input'; | |
@customElement( 'an-setname' ) | |
export class AnSetname extends LitElement { | |
render() { | |
return html` | |
<form | |
@submit="${ this._onSubmit }" | |
> | |
<an-input | |
name="xen" | |
required | |
>affi</an-input> | |
<button>Submit</button> | |
</form> | |
` | |
} | |
_onSubmit = ( event: SubmitEvent ) => { | |
event.preventDefault(); | |
console.log('form submitted even if required field is empty'); | |
} | |
} | |
declare global { | |
interface HTMLElementTagNameMap { | |
'an-setname': AnSetname, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment