A FormGroup helps you keep related form controls together. It makes managing and validating multiple inputs easier.
0
0
FormGroup for grouping controls in Angular
Introduction
When you have a form with several inputs that belong together, like name and email.
When you want to validate a group of controls as one unit.
When you want to enable or disable a set of controls together.
When you want to get or set values for multiple controls at once.
When you want to organize your form structure clearly.
Syntax
Angular
const myFormGroup = new FormGroup({ controlName1: new FormControl(''), controlName2: new FormControl(''), // add more controls here });
Each control inside FormGroup is a FormControl instance.
You can nest FormGroups inside other FormGroups for complex forms.
Examples
A simple login form with username and password controls grouped.
Angular
const loginForm = new FormGroup({ username: new FormControl(''), password: new FormControl('') });
Grouping address fields together for better structure.
Angular
const addressForm = new FormGroup({ street: new FormControl(''), city: new FormControl(''), zip: new FormControl('') });
Nested FormGroup for name inside a bigger profile form.
Angular
const profileForm = new FormGroup({ name: new FormGroup({ firstName: new FormControl(''), lastName: new FormControl('') }), email: new FormControl('') });
Sample Program
This Angular component creates a form with two controls grouped in a FormGroup. When you submit, it shows the entered values below the form.
Angular
import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-simple-form', template: ` <form [formGroup]="userForm" (ngSubmit)="submit()"> <label for="firstName">First Name:</label> <input id="firstName" formControlName="firstName" /> <label for="lastName">Last Name:</label> <input id="lastName" formControlName="lastName" /> <button type="submit">Submit</button> </form> <p *ngIf="submitted">You entered: {{ userForm.value | json }}</p> ` }) export class SimpleFormComponent { userForm = new FormGroup({ firstName: new FormControl(''), lastName: new FormControl('') }); submitted = false; submit() { this.submitted = true; } }
OutputSuccess
Important Notes
Use formControlName inside a form with [formGroup] to connect controls.
FormGroup helps track the overall form state like valid or dirty.
You can reset all controls in a FormGroup with formGroup.reset().
Summary
FormGroup groups related form controls for easier management.
It helps with validation, value access, and enabling/disabling controls together.
You connect controls in the template using formControlName inside a [formGroup].