Git Tutorial

Reactive Forms – Using FormGroup

In this tutorial, we will focus on Angular’s Reactive Forms and how to work with FormGroup to manage form inputs. Reactive forms are a powerful tool for managing form data, validation, and state in Angular applications. They provide more control compared to template-driven forms.

Now, let’s move on to creating the form in your component. We’ll use FormGroup to manage the form state.

  1. Import the necessary Reactive Forms classes:
    • FormGroup: To create a form group.
    • FormControl: To represent individual form controls.
  2. Create a FormGroup in your component:In your component (e.g., app.component.ts), create a FormGroup and initialize it with FormControl instances.
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Initialize the form group with individual form controls
userForm = new FormGroup({
name: new FormControl(''),
email: new FormControl(''),
age: new FormControl('')
});

// Function to handle form submission
onSubmit() {
console.log(this.userForm.value); // Output the form values to the console
}
}

Create the HTML Template

Now, in the app.component.html, you will bind the form to the template using Angular’s reactive form directives like formGroup and formControlName.

<div style="text-align:center">
<h1>Angular Reactive Form Example</h1>

<!-- Bind the form group to the form -->
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">

<!-- Name input field -->
<label for="name">Name:</label>
<input id="name" formControlName="name" />

<!-- Email input field -->
<label for="email">Email:</label>
<input id="email" formControlName="email" />

<!-- Age input field -->
<label for="age">Age:</label>
<input id="age" formControlName="age" />

<button type="submit">Submit</button>
</form>
</div>

Adding Form Validation (Optional)

Reactive forms also allow you to add validations to the form controls. For example, let’s add required validation to the form controls.

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Adding validation to the form controls
userForm = new FormGroup({
name: new FormControl('', Validators.required), // Name is required
email: new FormControl('', [Validators.required, Validators.email]), // Email is required and must be in email format
age: new FormControl('', Validators.required) // Age is required
});

onSubmit() {
if (this.userForm.valid) {
console.log(this.userForm.value); // Output form values if valid
} else {
console.log("Form is not valid");
}
}
}

In the HTML, you can display error messages if the form control is invalid.

<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<label for="name">Name:</label>
<input id="name" formControlName="name" />
<div *ngIf="userForm.controls.name.invalid && userForm.controls.name.touched">
Name is required.
</div>

<label for="email">Email:</label>
<input id="email" formControlName="email" />
<div *ngIf="userForm.controls.email.invalid && userForm.controls.email.touched">
Email is required and must be valid.
</div>

<label for="age">Age:</label>
<input id="age" formControlName="age" />
<div *ngIf="userForm.controls.age.invalid && userForm.controls.age.touched">
Age is required.
</div>

<button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>

Conclusion

  • FormGroup: A FormGroup is used to group form controls together and represent a form.
  • FormControl: A FormControl is an individual form field in a reactive form.
  • Validation: You can apply built-in validators like Validators.required, Validators.email, etc., or create custom validators.

This tutorial showed you how to set up a simple Angular reactive form using FormGroup and FormControl. You can extend this by adding more fields, applying more complex validation, and handling form submission accordingly.

1 thought on “Reactive Forms – Using FormGroup”

  1. Pingback: What Is Angular - Tech Mentor

Leave a Comment

Your email address will not be published. Required fields are marked *