AI Hints
Home›Angular Tutorial›FormGroup, Validators and Showing Errors
Angular · Lesson 85 of 120

FormGroup

Many fields together.

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

An order form has several fields. A name, and the number of copies. A form group keeps them together, as one form.

  • Several fields
  • Kept together
  • FormGroup

FormGroup

A form group holds named form controls. Form group, in square brackets, connects it to a form tag. Inside, form control name links each input to a control, by its name. And the group's value is one object, with every field.

keyvalue
new FormGroup({ ... })named controls
[formGroup]="order"on the form
formControlName="name"on each input
order.value{ name, copies }

An order form

The order group has two controls, name, and copies. The form tag is connected to the group, and each input to one control. On submit, send shows the group's value, as JSON. We type Sam, set copies to two, and click order. Run it. The value is one object, with both fields. And copies is a number, because the input type is number.

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

@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="order" (ngSubmit)="send()">
      <input formControlName="name" placeholder="Name">
      <input formControlName="copies" type="number"> <button>Order</button>
    </form>
    <p>{{ sent() }}</p>
  `,
})
export class App {
  order = new FormGroup({ name: new FormControl(''), copies: new FormControl(1) });
  sent = signal('');
  send() { this.sent.set(JSON.stringify(this.order.value)); }
}
Also uses actions.json
[{"type": "input[formcontrolname=name]", "text": "Sam"}, {"clear": "input[type=number]"}, {"type": "input[type=number]", "text": "2"}, {"click": "button"}]

Using FormBuilder

Form builder is a shortcut, for making groups. Inject it, then call group, with each field's starting value. It builds the same form group, with less typing.

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

@Component({ selector: 'app-root', template: `` })
export class App {
  private fb = inject(FormBuilder);

  order = this.fb.group({
    name: [''],
    copies: [1],
  });
}

Summary

A form group holds named controls, and its value is one object. Form builder makes groups with less typing. Next, validation rules.

Key takeaways
  • new FormGroup()
  • formControlName
  • FormBuilder
Next up: Validators — rules for fields