Sub topic 1
Quick recap: reactive forms
This chapter refreshes the parts of Angular reactive forms that FormArray builds on. If you can already write a FormGroup with validators and bind it in a template, skim it and move on. If any part feels shaky, fix it now, because every later chapter reuses these ideas.
Prerequisites
This chapter assumes you know the following:
- TypeScript basics: classes, generics, object types and arrow functions.
- Angular components and templates: the
@Componentdecorator, property binding and event binding. - Standalone components and how to list a module such as
ReactiveFormsModulein a component'simportsarray. - Basic reactive forms: that
FormControl,FormGroupandValidatorsexist and roughly what they do. This chapter recaps them but does not teach them from zero.
The examples use a current Angular release with standalone components, the inject() function and the @for and @if control-flow blocks.
The reactive model
In a reactive form, the form's structure and state live in your component class as objects. The template only displays and edits that model. This is the opposite of template-driven forms, where directives such as ngModel build the model implicitly from the HTML.
Keeping the model in code has three practical benefits:
- You can read and change the form from anywhere in the class, without touching the template.
- Validation rules sit next to the data they check.
- You can create, remove or replace parts of the form at runtime. This is what makes dynamic forms possible.
FormControl in brief
A FormControl tracks one value and the state of one input. It holds the current value, the validation result, and flags that describe what the user has done with it.
import { FormControl, Validators } from '@angular/forms';
const email = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
});
console.log(email.value);
console.log(email.valid);
email.setValue('[email protected]');
console.log(email.valid);This prints an empty string, then false (because required fails), then true.
The nonNullable: true option matters for typing. By default, reset() sets a control's value to null, so the control's type is string | null. With nonNullable: true, reset() returns the control to its initial value and the type stays string. This chapter uses nonNullable throughout, and the typed forms chapter explains the reasoning in detail.
FormGroup in brief
A FormGroup is a named collection of controls. Its value is an object with one property per control. Its validity depends on its children: the group is invalid if any child is invalid.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const profile = new FormGroup({
name: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
email: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
}),
});
console.log(profile.value);
console.log(profile.valid);
profile.patchValue({ name: 'Ada' });
console.log(profile.controls.name.value);The first log shows { name: '', email: '' } and the second shows false. After patchValue, the name control holds 'Ada'.
Because the structure is known at compile time, profile.controls.name is typed. A FormGroup is the right choice when you know the exact set of fields up front. Its keys are fixed names, and the shape does not change while the user works.
Control state
Every control, group and array exposes the same state properties. You will use them constantly when you decide when to show an error message.
| Property | Meaning |
|---|---|
| `value` | The current value. A group gives an object, an array gives an array. |
| `valid` / `invalid` | Whether all validators pass (for containers, all descendants too). |
| `pending` | An async validator is still running. |
| `disabled` | The control is excluded from validation and from `value`. |
| `touched` / `untouched` | The user has (or has not) focused and then left the control. |
| `dirty` / `pristine` | The user has (or has not) changed the value through the UI. |
| `errors` | An object of validation errors, or `null` when valid. |
State propagates upward. If one child control is invalid, its parent group is invalid. If one child is dirty, the parent is dirty. FormArray uses the same rules, so a list of entries reports a combined status automatically.
Validators
A validator is a function that receives a control and returns either null (valid) or an object that describes the error. Angular ships built-in validators in the Validators class, including required, email, min, max, minLength, maxLength and pattern.
You can pass one validator or an array of them. You can attach validators to a single control, or to a group or array to check a rule that involves several children. The validation chapter covers array-level validators in depth. For now, remember that a validator is just a function from a control to null or an error object.
FormBuilder
Writing new FormControl(...) and new FormGroup(...) repeatedly gets noisy. FormBuilder offers shorthand. The NonNullableFormBuilder variant applies nonNullable: true to every control it creates, so you do not have to repeat the option.
import { inject } from '@angular/core';
import { NonNullableFormBuilder, Validators } from '@angular/forms';
class Example {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
}In the array syntax, the first element is the initial value and the second is a validator or an array of validators. fb.group(), fb.control() and fb.array() are the three factory methods. The next chapters rely on fb.array().
Binding a form in the template
To connect the model to the HTML, you import ReactiveFormsModule and use its directives:
[formGroup]="form"on the<form>element connects aFormGroupto the markup.formControlName="name"on an input connects the input to the child control with that key.(ngSubmit)="save()"runs a handler when the form is submitted.
Here is a complete component that puts the pieces together.
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-profile-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="save()">
<label>
Name
<input formControlName="name" />
</label>
<label>
Email
<input type="email" formControlName="email" />
</label>
@if (form.controls.email.touched && form.controls.email.hasError('email')) {
<p>Enter a valid email address.</p>
}
<button type="submit" [disabled]="form.invalid">Save</button>
</form>
`,
})
export class ProfileFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
save() {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
console.log(this.form.getRawValue());
}
}Points worth noticing:
- The template never declares the fields. It refers to controls that already exist in the class.
hasError('email')checks for a specific validator key.markAllAsTouched()makes hidden errors appear when the user submits an incomplete form.getRawValue()returns the values of all controls, including disabled ones.valueleaves disabled controls out. The submit chapter returns to this difference.
Updating values from code
You have two methods for writing values into a group, and they differ in how strict they are:
setValue(obj)requires an object that matches the full shape of the group. A missing or extra key throws an error.patchValue(obj)accepts a partial object and updates only the keys you provide.
reset() returns controls to their initial value (with nonNullable) and marks them pristine and untouched. Each of these updates also emits on valueChanges, an observable that every control exposes. A later chapter uses it to react to changes.
Where a fixed FormGroup stops being enough
A FormGroup maps names to controls, and you write those names in the source code. That works for a form with a name and an email. It fails for questions like these:
- How does a user enter any number of email addresses?
- How does an order form hold one row per item, when the number of items is unknown until runtime?
You could invent keys such as email1, email2 and email3, and add controls with addControl(). That approach gets awkward fast. You would have to generate names, keep them in order, and rebuild the value into a list yourself. The model should instead mirror the data, which is an ordered list.
That is the job of FormArray. It holds an ordered sequence of controls, identified by position instead of by name. Its value is an array, and its validity is the combined validity of its entries. Everything in this chapter still applies: the same state flags, the same validators, the same FormBuilder. The next chapter shows how a FormArray fits into that model.
Exercise
A form has a "name" field and a variable number of "phone number" fields that the user can add or remove. Which part of this form fits a FormGroup, and which part needs something else? Give the reason.
Show answer
The "name" field fits a FormGroup, because it is one field with a fixed key known at compile time. The phone numbers need a FormArray, because the count changes at runtime and the entries are identified by position, not by name. The FormArray would sit inside the FormGroup as one of its controls, and its value would be an array of phone number strings.
Exercise
In a form built with NonNullableFormBuilder, a control has the initial value 'draft'. The user types 'final', and your code then calls reset() on the control. What is the control's value afterwards, and why?
Show answer
The value is 'draft'. A non-nullable control resets to its initial value instead of null. A control created without nonNullable would reset to null.