AI Hints
Home›Angular Tutorial›Forms in Angular, Template-Driven Forms and Reactive Forms
Angular · Lesson 84 of 120

Reactive Forms

Forms in the class.

⏱ 2 min read▶ Video at 1:40:19🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

In bigger forms, it's easier to build the form in the class, where code can read it, change it, and test it. That's what reactive forms do.

  • Bigger forms
  • Build it in the class
  • Reactive forms

Template-driven or reactive?

Template driven forms keep the setup in the template. Reactive forms keep it in the class, as objects. The class can set values, reset them, and add rules, without touching the template.

Template-driven

  • setup in the templatengModelquick to start

Reactive

  • setup in the classFormControleasy to change and test

FormControl

A form control is an object, for one field. It holds the value, and the field's state. Form control, in square brackets, connects it to an input. Set value, and reset, change it from code.

keyvalue
new FormControl('')one field
[formControl]="search"connect an input
.valuethe current value
.setValue(), .reset()change it from code

A form control

Search is a form control, starting empty. The input is connected to it. The paragraph shows its value. And two buttons change it from code. We type Dune, then click fill in Emma. Run it. The code replaced what we typed, and the input shows Emma.

app.tstypescript
import { Component } from '@angular/core';
import { ReactiveFormsModule, FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule],
  template: `
    <input [formControl]="search" placeholder="Search">
    <p>Value: "{{ search.value }}"</p>
    <button (click)="search.setValue('Emma')">Fill in Emma</button>
    <button (click)="search.reset()">Clear</button>
  `,
})
export class App {
  search = new FormControl('');
}
Also uses actions.json
[{"type": "input", "text": "Dune"}, {"click": "button"}]

Summary

Reactive forms live in the class. A form control holds one field, and code can set it, or reset it. Next, grouping fields together.

Key takeaways
  • new FormControl()
  • [formControl]
  • setValue(), reset()
Next up: FormGroup — many fields together