Reactive Forms – FormGroup Explained with Example

What is Form Group?

  1. FormGroup is used to control multiple form fields together
  2. Useful when form is large (many inputs)
  3. Easy to get, set, reset values at once


When to Use FormGroup?

  1. When you have 5–20 input fields
  2. When you want full form control
  3. When you want validation, reset, submit easily


Required Imports (Important)

import { ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms';


Component Code

loginForm = new FormGroup({
name: new FormControl(''),
email: new FormControl(''),
password: new FormControl('')
});

handleProfile() {
console.log(this.loginForm.value);
}

reset() {
this.loginForm.setValue({
name: '',
email: '',
password: ''
});
}


HTML Code

<form [formGroup]="loginForm" (ngSubmit)="handleProfile()">

<input type="text" placeholder="Enter Name" formControlName="name">
<br><br>

<input type="email" placeholder="Enter Email" formControlName="email">
<br><br>

<input type="password" placeholder="Enter Password" formControlName="password">
<br><br>

<button type="submit">Submit</button>
<button type="button" (click)="reset()">Reset</button>

</form>


<ul>
<li>Name: {{ loginForm.value.name }}</li>
<li>Email: {{ loginForm.value.email }}</li>
<li>Password: {{ loginForm.value.password }}</li>
</ul>