Sub topic 8
Handling ngSubmit and resetting the form
This chapter assumes you can bind inputs with ngModel, read a form through #f="ngForm", and apply built-in validators such as required. Here you will submit the form safely and return it to a clean state.
What ngSubmit does
When a <form> contains FormsModule, Angular attaches an NgForm directive to it. NgForm listens for the browser's native submit event and does two things:
- It sets
f.submittedtotrue. - It emits the
ngSubmitoutput and cancels the native submit, so the page does not reload.
Bind to (ngSubmit) instead of (submit) or a click handler on the button. This way Enter-key submission also reaches your code, and you get the submitted flag.
A complete example
The component passes the form to the handler, shows errors after a submit attempt, and resets after a successful save.
import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-contact',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<label for="name">Name</label>
<input id="name" name="name" [(ngModel)]="model.name"
#name="ngModel" required />
@if (name.invalid && (name.touched || f.submitted)) {
<p role="alert">Name is required.</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">Send</button>
<button type="button" (click)="onReset(f)">Clear</button>
</form>
@if (saved) {
<p>Saved: {{ saved }}</p>
}
`,
})
export class ContactComponent {
private readonly initial = { name: '', email: '' };
model = { ...this.initial };
saved = '';
onSubmit(f: NgForm) {
if (f.invalid) {
return;
}
this.saved = JSON.stringify(f.value);
f.resetForm({ ...this.initial });
}
onReset(f: NgForm) {
f.resetForm({ ...this.initial });
this.saved = '';
}
}Three details matter in this code:
novalidateturns off the browser's own validation bubbles, so your messages are the only ones shown. Angular adds this attribute automatically in most cases, but writing it makes the intent clear.f.submittedlets you show errors for untouched fields after the user presses Send. Without it, a user who clicks Send on an empty form sees nothing.- The guard
if (f.invalid) return;protects against submission when the button is not disabled, for example through the Enter key.
resetForm versus reset
NgForm offers two ways to clear a form. They differ in one important way.
| Call | Control values | pristine / untouched | `submitted` |
|---|---|---|---|
| `f.reset()` | Set to `null` | Restored | Not changed |
| `f.resetForm()` | Set to `null` | Restored | Set to `false` |
| `f.resetForm({ name: '' })` | Set from the object | Restored | Set to `false` |
Prefer resetForm. If submitted stays true, your error messages reappear on the empty form immediately after a successful save.
Common errors
- Page reloads on submit. The form is missing
FormsModule, soNgFormis not attached and the native submit runs. - Controls ignored. An input without a
nameattribute inside a form throws an error at runtime, becausengModelregisters the control under that name. - Errors persist after reset. You used
reset()and notresetForm(), sosubmittedstayedtrue.
Exercise
A user clicks Send on an empty form, but no error messages appear. The error blocks use the condition name.invalid && name.touched. What change fixes this, and why does the problem happen?
Show answer
Add || f.submitted to the condition, as in name.invalid && (name.touched || f.submitted). The user never focused or left the field, so touched is still false. Pressing Send sets f.submitted to true, which makes the message appear.
Exercise
After a successful save, you call f.reset() and the required-field errors flash on the cleared form. Which call should you use instead, and what does it change?
Show answer
Use f.resetForm(), ideally with the initial values. Unlike reset(), it also sets f.submitted back to false, so the error condition no longer holds.