... Create some TypeScript class :" /> ... Create some TypeScript class :" /> ... Create some TypeScript class :"/>

HTML Form and Typescript class handler

214 Views Asked by At

I would like to bind a onSubmit form event to a TypeScript class method :

<form onsubmit="onSubmit(event)">
    ...
</form>

Create some TypeScript class :

export class FormHandler {
    public static onSubmit(event: any): void {
        event.preventDefault()
        console.log('Form was submitted')
    }
}
export const onSubmit = (event: any) => FormHandler.onSubmit(event)

But, raised an "uncaught" error, onSubmit property not found.

My question is so, how to bind a class method to the onsubmit form event with TypeScript ?

Regards

1

There are 1 best solutions below

0
ErnestasL On

I suggest you do not add events like this and instead use the addEventListener API. And you would need to initialize your FormHandler.

class FormHandler {
  public onSubmit(event: Event): void {
    event.preventDefault();
    console.log('Form was submitted');
  }
}

const formHandler = new FormHandler();

const form = document.querySelector('form');
form.addEventListener('submit', (event) => formHandler.onSubmit(event));