Example 1: Form Handling using Template Driven forms.
In this example, we’ll see form submission and handling of form data using Template Driven forms.
Step 1: Create a new Angular project by running the below command.
ng new <project_name>
Folder Structure:
Dependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/platform-server": "^17.3.0",
"@angular/router": "^17.3.0",
"@angular/ssr": "^17.3.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.0",
"@angular/cli": "^17.3.0",
"@angular/compiler-cli": "^17.3.0",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0",
"@types/node": "^18.18.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}
Code Example: Add the following codes in the required files.
<!-- app.component.html -->
<form #userForm="ngForm" (ngSubmit)="onSubmit()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" [(ngModel)]="user.name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" [(ngModel)]="user.email" required>
<button type="submit">Submit</button>
</form>
<h3>User Details</h3>
<p>{{userDetails}}</p>
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
user = { name: '', email: '' };
userDetails = 'Loading...';
onSubmit() {
this.userDetails =
'User name is ' + this.user.name + ' and email is ' + this.user.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.
Contact Us