hilla

How to set the value of a vaadin select with Typesript?


I have a form and after I submit the data I want to reset the data to the original state. But I don't find any specific function to do that.

select?.value = "asdf"; // not allowed
select?.setAttribute("value", value); // only works once

Is there a trick with that I can set the value with Typescript?


Solution

  • To reset a select element's value in TypeScript, you can use HTMLSelectElement type casting:

    const select = document.querySelector('select') as HTMLSelectElement;
    select.value = "default"; // This will work
    

    Or if you're using optional chaining:

    (select as HTMLSelectElement)?.value = "default";
    

    This is the most straightforward and reliable way to set select values in TypeScript. The key is proper type casting to HTMLSelectElement.