Example 2: Form Handling using Reactive Forms.
In this example, we’ll see form submission and handling of form data using Reactive forms.
Code Example: Add the following codes in the respective files.
<!-- app.component.html -->
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<label for="name">Name:</label>
<input type="text" id="name" formControlName="name">
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email">
<button type="submit">Submit</button>
</form>
<h3>Form Details</h3>
<p>{{formDetails}}</p>
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, ReactiveFormsModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
//app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
myForm: FormGroup = {} as FormGroup;
formDetails: string = 'loading...';
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
name: ['', [Validators.required]],
email: ['', [Validators.required, Validators.email]],
});
}
onSubmit() {
this.formDetails =
'Name: ' + this.myForm.value.name + ' Email:' + this.myForm.value.email;
}
}
Output:
Purpose of the FormsModule in Angular
Forms are widely used in web applications that allow you to provide the data, submit the forms, and interact with the application. In Angular for handling the forms, we use Forms Module which imports several powerful tools for creating, managing, and validating forms. In this article, we’ll cover the purpose of the forms module, syntax, concepts, and examples related to Angular forms.
Table of Content
- What is FormsModule?
- Type of Forms
- Purpose of Forms Module
- Form Handling using Template Driven forms.
- Form Handling using Reactive Forms.