Angular - FormModule functionality

Discussão em 'Angular' iniciado por Freezy, Fevereiro 18, 2025.

  1. Freezy

    Freezy Guest

    I'm experimenting with Angular modules, and I'm currently working with FormModule. I noticed that once FormModule is imported into a component, the <form/> submit event no longer refreshes the page, as if $event.preventDefault is automatically applied. This behavior is the same whether I use the (submit) or (ngSubmit) event, and regardless of whether the button has type='submit' or type='button', the page never refreshes.

    I checked the source code of NgForm and found this function:

    onSubmit($event: Event): boolean {
    this.submittedReactive.set(true);
    syncPendingControls(this.form, this._directives);
    this.ngSubmit.emit($event);
    // Forms with `method="dialog"` have some special behavior
    // that won't reload the page and that shouldn't be prevented.
    return ($event?.target as HTMLFormElement | null)?.method === 'dialog';
    }


    I created a dialog component with <button type='submit' />, and upon submission, the dialog closed. This suggests that preventDefault was executed, because when I specify <button type='button' /> or manually call preventDefault on the form (submit), the dialog does not close.

    I haven't been able to find the exact code block where Angular controls the preventDefault behavior, nor have I found an explanation in the documentation. Has anyone looked into this in depth? Is this managed by Angular’s event binding, or something else?

    Continue reading...

Compartilhe esta Página