Building Template-Driven Form in Angular
Last Updated :
15 Jul, 2024
In Template Driven Forms we specify behaviors/validations using directives and attributes in our template and let it work behind the scenes. All things happen in Templates hence very little code is required in the component class. This is different from the reactive forms, where we define the logic and controls in the component class.
- The form is set up using ngForm directive.
- Controls are set up using the ngModel directive.
- ngModel provides the two-way data binding.
- The Validations are configured in the template via directives.
Steps To Build Template-Deiven Form
Step 1: Create a root directory called Form using the following command:
mkdir Form
Step 2: Navigate to the root directory. Run the following command to initialize a new Angular app:
npm install -g @angular/cli
cd From
ng new my-angular-form-project
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/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Folder Structure
Folder StructureExample: In this example we are creating a basic Template-Driven Form
HTML
<!-- src/app/app.component.html -->
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
<p>
<label for="firstname">First Name</label>
<input type="text" name="firstname" ngModel #fname="ngModel">
</p>
<p>
<label for="lastname">Last Name</label>
<input type="text" name="lastname" ngModel>
</p>
<p>
<label for="email">Email </label>
<input type="text" id="email" name="email" ngModel>
</p>
<p>
<label for="gender">Gender</label>
<input type="radio" value="male" name="gender" ngModel> Male
<input type="radio" value="female" name="gender" ngModel> Female
</p>
<p>
<label for="isMarried">Married</label>
<input type="checkbox" name="isMarried" ngModel>
</p>
<p>
<label for="country">Country</label>
<select name="country" ngModel>
<option [ngValue]="c.id" *ngFor="let c of countryList">
{{c.name}}
</option>
</select>
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
CSS
/* src/app/app.component.css */
body {
background: #f3f3f3;
text-align: center;
}
.App {
background-color: #fff;
border-radius: 15px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
padding: 10px 20px;
transition: transform 0.2s;
width: 500px;
text-align: center;
margin: auto;
margin-top: 20px;
}
h1 {
font-size: x-large;
text-align: center;
color: #327c35;
}
fieldset {
border: none;
}
input {
display: block;
width: 100%;
/* margin-bottom: 15px; */
padding: 8px;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 3px;
font-size: 12px;
}
input[type="radio"],
input[type="checkbox"] {
display: inline;
width: 10%;
}
select {
display: block;
width: 100%;
margin-bottom: 15px;
padding: 10px;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 5px;
}
label {
font-size: 15px;
display: block;
width: 100%;
margin-top: 8px;
margin-bottom: 5px;
text-align: left;
color: #555;
font-weight: bold;
}
button {
padding: 15px;
border-radius: 10px;
margin: 15px;
border: none;
color: white;
cursor: pointer;
background-color: #4caf50;
width: 40%;
font-size: 16px;
}
textarea {
resize: none;
width: 98%;
min-height: 100px;
max-height: 150px;
}
JavaScript
// src/app/app.component.ts
import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [CommonModule, FormsModule],
standalone: true,
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = "my-angular-form-project";
countryList: country[] = [
new country('1', 'India'),
new country('2', 'USA'),
new country('3', 'England'),
];
onSubmit(contactForm: NgForm) {
// Your form submission logic here
console.log('Form Submitted!', contactForm.value);
}
}
export class country {
id: string;
name: string;
constructor(id: string, name: string) {
this.id = id;
this.name = name;
}
}
To run the application, type the following command:
ng serve
Output
Building Template-Driven Form in AngularBenefits of Template-Driven Forms
- Simplicity: Template-driven forms are simple to set up and use, making them ideal for smaller or less complex forms. They allow you to define your form in the template, which can be more intuitive for developers familiar with HTML.
- Two-Way Data Binding: With Angular’s two-way data binding, template-driven forms can automatically update the model as the user interacts with the form. This feature reduces boilerplate code and makes it easier to manage form data.
- Built-In Validation: Angular’s built-in validators can be easily applied to form controls using attributes like
required
, minlength
, maxlength
, and more. Custom validators can also be added if needed. - Integration with Angular Directives: Template-driven forms uses Angular’s powerful directives, such as
ngModel
, ngSubmit
, and ngForm
, to create and manage forms efficiently.
Similar Reads
Create A Template Driven Form In Angular Template Driven Form in Angular means managing form input and validation primarily through HTML templates, using Angular directives like ngModel for two-way data binding and ngForm for form management. This approach is ideal for simpler forms where most of the logic and validation are handled direct
4 min read
Template Driven Form vs Reactive Form in Angular. Angular provides two main approaches for creating forms: Template-Driven Forms and Reactive Forms. In this article, we'll see both methods, highlighting their features, and providing code examples. We'll also compare them side by side to help you understand when to use each. Template-Driven FormTemp
4 min read
Angular PrimeNG Form Chips Templates Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use Angular PrimeNG Form Chips Templates Component. The Chips compo
3 min read
Angular PrimeNG Form Chips Template Component Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use the calendar component in angular ngx bootstrap. Â Chips Templat
3 min read
Angular PrimeNG Form Dropdown Templates Component Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the Form Dropdown Templates Component in Angular PrimeNG. Th
4 min read
Angular forms NgModel Directive In this article, we are going to see what is NgModel in Angular 10 and how to use it. NgModel is used to create a top-level form group Instance, and it binds the form to the given form value. Syntax: <Input [(NgModel)= 'name']> NgModule: Module used by NgModel is: FormsModule Selectors: [ngMod
1 min read
Building Complex Forms Using Angular Reactive Form Imagine you are building a web page where you have to make a Form having fields, such as First Name, Last Name, and so on and you have to handle form inputs, validations, and interactions. Here, using Reactive Forms you define the structure of the form directly in Typescript code rather than HTML te
7 min read
Angular FormsModule Directive In this article, we are going to see what is FormsModule in Angular 10 and how to use it. The FormsModule is used to make all the necessary imports for form implementation. Syntax: import { FormsModule } from '@angular/forms'; Approach:Â Create an Angular app to be used.In app.component.ts import fo
1 min read
Angular PrimeNG Form Inputtext Model Binding Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the InputText Component in Angular PrimeNG. Letâs learn abo
3 min read
Angular forms NgForm Directive In this article, we are going to see what is NgForm in Angular 10 and how to use it. NgForm is used to create a top-level form group Instance, and it binds the form to the given form value. Syntax: <form #FormName = "ngForm"> </form> NgModule: Module used by NgForm is: FormsModule Select
1 min read