Sub topic 8
Handling ngSubmit and resetting the form
This chapter assumes you can already bind inputs with [(ngModel)], give each control a name, and read control state through template reference variables such as #name="ngModel" and #f="ngForm". It covers what happens when the user submits, how to validate at that moment, and how to reset the form without leaving the model in a bad state.
What ngSubmit does
When you import FormsModule, Angular attaches the NgForm directive to every <form> element that has no action attribute. NgForm listens for the browser's native submit event and does three things:
- It sets
f.submittedtotrue. - It emits the
ngSubmitoutput. - It returns
falsefrom the listener, which cancels the default browser behavior. The page does not reload.
ngSubmit fires whether the form is valid or not. Angular does not block the submission for you. Validity is something your handler or your template has to check.
Angular also adds the novalidate attribute to the form. The browser's own validation bubbles never appear, so the error display is entirely under your control.
A native submit event happens in two situations:
- The user clicks a
<button type="submit">inside the form. - The user presses Enter inside a text input. This works when the form has a submit button, or when it has only one text field. If the submit button is disabled, most browsers do not submit on Enter.
A <button> inside a form defaults to type="submit". Give every other button type="button", or it will submit the form by accident.
The submitted flag
f.submitted stays true after the first submit until the form is reset. It is the usual way to show errors on fields the user never touched. The touched and dirty checks from the previous chapters do not cover that case. A user who clicks Save on an empty form has touched nothing.
The flag follows a small state machine.
A complete submit handler
The component below shows three habits:
- It passes the
NgForminto the handler. - It checks validity inside the handler, not only in the template.
- It guards against double submission while an asynchronous save is running.
import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-signup',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<label for="name">Name</label>
<input
id="name"
name="name"
[(ngModel)]="model.name"
#name="ngModel"
required
minlength="3"
/>
@if (name.invalid && (name.touched || f.submitted)) {
<p role="alert">Name is required and needs at least 3 characters.</p>
}
<label for="email">Email</label>
<input
id="email"
name="email"
type="email"
[(ngModel)]="model.email"
#email="ngModel"
required
email
/>
@if (email.invalid && (email.touched || f.submitted)) {
<p role="alert">Enter a valid email address.</p>
}
<button type="submit" [disabled]="saving">
{{ saving ? 'Saving...' : 'Save' }}
</button>
<button type="button" (click)="f.resetForm({ name: '', email: '' })">
Clear
</button>
</form>
@if (message) {
<p>{{ message }}</p>
}
`,
})
export class SignupComponent {
model = { name: '', email: '' };
saving = false;
message = '';
async onSubmit(form: NgForm) {
if (this.saving) {
return;
}
if (form.invalid) {
form.control.markAllAsTouched();
return;
}
this.saving = true;
try {
await new Promise((resolve) => setTimeout(resolve, 500));
this.message = `Saved ${form.value.name}`;
form.resetForm({ name: '', email: '' });
} finally {
this.saving = false;
}
}
}Points to notice in this code:
- The error condition is
name.invalid && (name.touched || f.submitted). Errors appear after the user leaves the field, or after any submit attempt. form.control.markAllAsTouched()is an alternative to thef.submittedcheck. It marks every control as touched, so templates that only testtouchedalso show their errors. Use it when you cannot change the templates.- The Save button is disabled only while saving. It is not disabled when the form is invalid. A button disabled for invalid input gives the user no hint about what is wrong. It also prevents Enter-key submission, so the
submittedflag never becomestrueand no errors appear. - The
if (this.saving) return;guard covers double-clicks and repeated Enter presses that arrive before the button re-renders as disabled. form.valueis an object keyed by controlname. It contains only controls registered withngModel, and it leaves out disabled controls. Yourmodelobject may hold more properties thanform.valuedoes.
Which value to send: model or form.value
Because the inputs use [(ngModel)], this.model and form.value normally hold the same data for the registered fields. Pick one source and use it consistently:
- Use
this.modelwhen the object is already shaped like your API payload. - Use
form.valuewhen you want only what the form controls actually hold, or when you usengModelGroupand want the nested shape. The next chapters cover groups.
Ngmodel updates the model on each input event, so by the time ngSubmit fires, both are current.
Resetting the form
There are three ways to reset, and they differ in what they clear.
| Call | Values | touched, dirty, pristine | `f.submitted` |
|---|---|---|---|
| `f.resetForm()` | Set to `null` | Reset | Set to `false` |
| `f.resetForm({ name: '' })` | Set to the object you pass | Reset | Set to `false` |
| `f.reset()` or `f.form.reset()` | Set to `null` | Reset | Unchanged |
A native <button type="reset"> fires the form's reset event, which NgForm handles by calling resetForm(). That gives the same result as the first row.
resetForm is almost always the right call, because it also clears submitted. If you use f.reset() and your errors depend on f.submitted, the form will show a wall of errors right after a successful save.
Reset and validation state
After a reset, controls return to pristine and untouched. They are still validated. An empty required field is invalid right after the reset, so f.invalid is true. The error messages stay hidden only because your display condition (touched || submitted) is now false. This is the reason to build messages on those two flags rather than on invalid alone.
Resetting in the right place
Reset after the work succeeds, not at the start of the handler. If the save fails, the user keeps what they typed and can retry. The example calls resetForm after the awaited save. On failure the await throws, finally clears saving, and the form keeps its values. In real code, add a catch that sets an error message.
Do not reset a form from inside a (ngModelChange) handler or during change detection. That can trigger ExpressionChangedAfterItHasBeenChecked errors. Reset from event handlers such as ngSubmit or a click.
Common errors
- The page reloads on submit. The form has an
actionattribute, soNgFormis not attached and nothing cancels the native submission. Removeaction, or make sureFormsModuleis in the component'simports. ngSubmitnever fires. The submit button sits outside the<form>element, or it hastype="button".- Controls are missing from
f.value. AnngModelinput without anameattribute throws an error when it is inside a form. A control whosenameis set through a standalone option is not registered. Give every control a uniquename. - Errors show on page load. The display condition tests
invalidalone. Addtouched || f.submitted. - Reset leaves old error text on screen. You called
f.reset()and thesubmittedflag stayedtrue. UseresetForm().
Exercise
A user opens the signup form and presses Enter without typing anything. The Save button is disabled with [disabled]="f.invalid", and the error messages are shown when name.invalid && (name.touched || f.submitted). Why does the user see no error messages, and what is the smallest change that fixes it?
Show answer
The disabled submit button blocks implicit submission through the Enter key, so ngSubmit never fires and f.submitted stays false. The fields are also untouched, so the error condition is false. Change the button to [disabled]="saving" (or remove the binding) so that submitting is possible. The handler then runs, f.submitted becomes true, and the errors appear. Also check form.invalid in the handler.
Exercise
After a successful save, your handler calls form.reset(). Immediately afterwards every field shows its "required" error, and model.name is null. Name both problems and give one call that fixes both.
Show answer
form.reset() does not set f.submitted back to false, so the submitted part of the error condition stays true and shows errors on the now-empty fields. It also writes null into the bound model properties. Calling form.resetForm({ name: '', email: '' }) clears submitted and sets the model values to empty strings.