Difference between the event (Submit) and (ngSubmit)

Asked

Viewed 131 times

2

Well, I’ve seen some articles explaining that "ngSubmit ensures that the form is not sent when the handler code is released (which is the default sending behavior) and causes a real http posting request."

I honestly didn’t understand anything.

What is the difference between these two events?

  • Submit causa postBack, ie reload the page. ngSubmit basically prevents standard Ubmit compartmentalization, having greater control in a SPA application.

2 answers

2


The problem is in the translation you mentioned. The original passage says:

ngSubmit Ensures that the form doesn’t Submit when the Handler code throws (which is the default behaviour of Submit) and causes an actual http post request.

The part that matters is "handler code throws", this refers to exceptions, example:

if (this.formControls.sellingDate > today) {
    throw new Error("Campo data não pode ser maior que hoje.");
}

The translation "é lançado" really not a good translation for "throws", and that’s where it’s causing doubt.

However, I do not advise you to validate forms using exceptions, try using Validators in your formControls or even use toastr to notify the user about the problem with the data informed in a more friendly way.

Another point is that to avoid reloads, if that is your problem, you have two options that I consider best:

  • pass the $event for your method ("handler") and call $event.preventDefault(); in the first line; or
  • when entering an "if" that is impeditive, use return false; right after giving the message to the user.

I hope I’ve helped.

1

The final part of the standard behavior of the event Submit() of a form is the sending of the contents of the form to the destination specified in the attribute action, following a page reload.

This reload goes against the desired behavior in a single-page application - in case your Angular application should only send the content and wait for the return without Reload.

  • Yes, but in Angular2+ there are two events, Ubmit and ngSubmit. The two submit the data and the two do not reload the page. I wanted to know the difference between these Binding Vents

Browser other questions tagged

You are not signed in. Login or sign up in order to post.