Reactive Forms – FormGroup Explained with Example
What is Form Group?
- FormGroup is used to control multiple form fields together
- Useful when form is large (many inputs)
- Easy to get, set, reset values at once
When to Use FormGroup?
- When you have 5–20 input fields
- When you want full form control
- 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>