Sub topic 4
The form as a whole: NgForm and #f="ngForm"
This chapter assumes you know Angular standalone components, template reference variables, event binding, and basic HTML forms. It also assumes you have already imported FormsModule and bound an input with ngModel. Here you will learn how Angular turns a plain <form> element into a form model, and how to read that model from your template.
What NgForm does
When FormsModule is imported, Angular attaches an NgForm directive to every <form> element that does not have a formGroup binding. You do not write ngForm in the template. The directive matches the form tag on its own.
NgForm does three jobs:
- It creates a top-level
FormGroup, which is the object that holds the state of every control inside the form. - It collects each
ngModelinput as a child control, using the input'snameattribute as the key. - It listens for the native
submitevent and re-emits it asngSubmit.
Because NgForm owns the group, the group's value, validity, and flags (dirty, touched, pristine) reflect all the controls together. If one control is invalid, the whole form is invalid.
Exporting the directive with #f="ngForm"
A bare #f on an element gives you the DOM element, here an HTMLFormElement. That object has no Angular state. To get the directive instance instead, write #f="ngForm". The string after = is the directive's exportAs name. It tells Angular: "set this variable to the directive, not the element."
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-contact',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="email">Email</label>
<input id="email" name="email" [(ngModel)]="model.email" required email />
<label for="message">Message</label>
<textarea id="message" name="message" [(ngModel)]="model.message" required></textarea>
<button type="submit" [disabled]="f.invalid">Send</button>
<pre>valid: {{ f.valid }}
dirty: {{ f.dirty }}
touched: {{ f.touched }}
value: {{ f.value | json }}</pre>
</form>
`,
})
export class ContactComponent {
model = { email: '', message: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}The variable f is only visible inside the template. It is also visible to anything in the same template scope, so you can use it on the submit button, in @if blocks, and in other elements. You cannot read it from the class unless you pass it in (see the next section) or query for it.
What you can read from the form
f is an NgForm, and it forwards most of the FormGroup API. The members you will use most are:
| Member | Type | Meaning |
|---|---|---|
| `f.value` | object | Current values of all controls, keyed by `name` |
| `f.valid` / `f.invalid` | boolean | True when every control passes validation |
| `f.pending` | boolean | True while an async validator is running |
| `f.dirty` / `f.pristine` | boolean | Whether the user has changed any value |
| `f.touched` / `f.untouched` | boolean | Whether any control has lost focus |
| `f.submitted` | boolean | True after the form has been submitted, until reset |
| `f.controls` | object | The child controls, keyed by `name` |
| `f.errors` | object or null | Errors on the form group itself (not on children) |
Two points are easy to miss.
First, f.valid is false if any child is invalid, but f.errors only contains errors set on the group itself, for example by a cross-field validator. A form can be invalid while f.errors is null.
Second, f.submitted stays true after the first submit. It is useful for showing errors only after the user has tried to send the form. resetForm() sets it back to false.
Passing the form to a handler
Often the handler needs the form object, not just the model. Pass the template variable as an argument:
<form #f="ngForm" (ngSubmit)="save(f)">
<input name="title" [(ngModel)]="model.title" required />
<button type="submit">Save</button>
</form>import { NgForm } from '@angular/forms';
save(form: NgForm) {
if (form.invalid) {
return;
}
console.log(form.value);
}Guarding on form.invalid inside the handler matters even if the button is disabled. Users can press Enter in a text field and trigger a submit, and a disabled button does not always block that in every browser and markup structure. The guard is cheap and keeps invalid data out of your code.
Reading the form from the class with viewChild
If you need the form inside a method that is not triggered by a template event, use viewChild:
import { Component, viewChild } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-profile',
imports: [FormsModule],
template: `
<form #f="ngForm">
<input name="nickname" [(ngModel)]="model.nickname" required />
</form>
<button type="button" (click)="check()">Check</button>
`,
})
export class ProfileComponent {
model = { nickname: '' };
form = viewChild.required<NgForm>('f');
check() {
console.log(this.form().valid, this.form().value);
}
}viewChild.required returns a signal, so you call it like a function. The query resolves after the view is created. Do not read it in the constructor.
Why every control needs a name
Inside a <form>, every element with ngModel must have a name attribute. NgForm uses that string as the control's key in the group. If the name is missing, Angular throws an error at runtime that says the control must have a name when used inside a form.
Two controls with the same name share one entry in the group. This is the correct behavior for radio buttons, which are a single control with several options. For other inputs it is a bug: the values overwrite each other.
The name does not need to match the model property. In name="email" [(ngModel)]="model.contactEmail", the form value will have an email key, while the component writes to model.contactEmail. Keeping them equal makes the code easier to read.
Form value versus your model
There are two copies of the data, and they are not the same object.
modelis your plain object.[(ngModel)]writes to it as the user types.f.valueis a new object built from the form controls. It is keyed byname, not by your model's property names.
Prefer your own model when you send data to a server, because its shape is under your control. Use f.value when you want exactly what the form currently holds, for example for debugging.
One subtle point: ngModel updates the control asynchronously on first render. If you read f.value in ngOnInit or in the constructor, it will be empty. The controls register in a microtask after the first change detection. Read it in a handler or after the view has settled.
Timing: when the form becomes valid
The form's validity is recalculated every time a control's value or validators change. For the common case, you can rely on f.valid directly in the template. When you add an async validator, f.valid is false while the check runs, and f.pending is true. A submit button that only checks f.invalid will be enabled during pending state, because invalid is false while pending is true. If you use async validators, disable the button on both:
<button type="submit" [disabled]="f.invalid || f.pending">Save</button>Common errors
- Writing
#finstead of#f="ngForm". Thenf.validisundefined, becausefis the DOM form element. The template silently shows nothing or an always-enabled button. - Forgetting
nameon anngModelinput. The view throws at creation time. - Using
f.valueas if it mirrored your model's shape. It mirrors thenameattributes (andngModelGroupnames). - Reading
fbefore it exists. A template variable cannot be used above the element that declares it in some structural contexts, such as inside an@ifblock that is a sibling rather than a descendant of the form. - Putting the submit button outside the
<form>without aform="..."attribute. The submit event never reachesngSubmit.
Summary of the flow
Exercise
A teammate writes <form #f (ngSubmit)="save()"> and uses <button [disabled]="f.invalid">. The button is always enabled, even when required fields are empty. What is wrong, and how do you fix it?
Show answer
#f without a value refers to the DOM HTMLFormElement, which has no invalid property, so f.invalid is undefined and falsy. Change it to #f="ngForm" so f refers to the NgForm directive, whose invalid property reflects the validity of all controls.
Exercise
A form has two inputs, both with [(ngModel)] and name="phone", one for a home number and one for a work number. Only one value shows up in f.value. Why, and what is the fix?
Show answer
Controls with the same name share one key in the form group, so they overwrite each other. Give each input a unique name, such as homePhone and workPhone, or group them under separate ngModelGroup names.
Exercise
Your form uses an async validator, and users sometimes submit before the check finishes. Which flag do you add to the button's [disabled] expression, and why isn't f.invalid enough?
Show answer
Add f.pending, as in [disabled]="f.invalid || f.pending". While an async validator runs, the status is PENDING, so invalid is false and the button would be enabled.