Reputation: 59
I am defining a custom text input component in lit (ie: <custom-textinput>
)
I want a custom property called type
which is "text" by default but the developer can pass in text | number | email | tel
which are all valid inputs on the standard html <input>
This is my current code:
@customElement("custom-textinput")
export class CustomTextInput extends LitElement {
@property({ type: String }) type: "text" | "number" | "email" | "tel" = "text";
render() {
return html`
<input type = ${this.type}/>
`
}
Other types should be restricted (ie: radio
button
checkbox
) because I am creating different components for them. However right now, when I use <custom-textinput>
and for testing purposes do <custom-textinput type="radio">
it renders the radiobutton input instead of defaulting to type="text
because I did not include "radio" as an option in my type property. How can I restrict this to only allow my predetermined types and not anything that is valid on the standard html <input>
element?
Upvotes: 4
Views: 73
Reputation: 1186
You can create a custom accessor to only allow certain values.
const VALID_TYPE = new Set(['text', 'number', 'email', 'tel']);
@customElement("custom-textinput")
export class CustomTextInput extends LitElement {
#type: "text" | "number" | "email" | "tel" = "text";
@property()
set type(val: string) {
if (VALID_TYPE.has(val)) {
this.#type = val;
} else {
console.warn(`Tried to set invalid type: "${val}". Defaulting to "text".`);
this.#type = "text";
}
}
get type() {
return this.#type;
}
render() {
return html`
<input type = ${this.type}/>
`
}
Upvotes: 1