Angular / Angular Forms and Validation

Building Template-Driven Forms

In this tutorial, you'll learn how to build Template-Driven Forms in Angular. These forms are an essential part of any Angular application, and understanding them will improve you…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers creating and validating forms using Angular forms module.

1. Introduction

In this tutorial, we aim to guide you on how to build Template-Driven Forms in Angular. Template-Driven forms are a simple way to use Angular's form capabilities and are quite powerful in their own right. They are useful for collecting and handling user input in a structured and organized manner.

By the end of this tutorial, you'll learn:

  • How to create a template-driven form
  • How to use two-way data binding
  • How to validate form inputs
  • How to handle form submission

Prerequisites:
- A basic understanding of HTML, CSS, and TypeScript.
- A basic knowledge of Angular and its Framework.

2. Step-by-Step Guide

Creating a template-driven form involves the following steps:

1. Importing FormsModule

In order to use template-driven forms, we need to import FormsModule into our application module.

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule
  ]
})
export class AppModule { }

2. Creating the form template

We will create a simple form template with a few fields. In a template-driven approach, the template is the source of truth. We use ngModel to create two-way data bindings for reading and writing input-control values.

<form>
  <label>
    Name:
    <input type="text" [(ngModel)]="name" name="name">
  </label>
  <label>
    Email:
    <input type="email" [(ngModel)]="email" name="email">
  </label>
  <button type="submit">Submit</button>
</form>

3. Accessing the form

To access the form, we will use ngForm directive. We will also use ngSubmit event to handle form submission.

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
...
</form>

4. Form Validations

Angular provides several built-in validators such as required, email, minlength, etc. Let's add some to our form.

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
  <label>
    Name:
    <input type="text" [(ngModel)]="name" name="name" required>
  </label>
  <label>
    Email:
    <input type="email" [(ngModel)]="email" name="email" required email>
  </label>
  <button type="submit" [disabled]="myForm.form.invalid">Submit</button>
</form>

3. Code Examples

Let's look at an example of a complete template-driven form.

1. app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = '';
  email = '';

  onSubmit(form) {
    console.log(form.value);
  }
}

3. app.component.html

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
  <label>
    Name:
    <input type="text" [(ngModel)]="name" name="name" required>
  </label>
  <label>
    Email:
    <input type="email" [(ngModel)]="email" name="email" required email>
  </label>
  <button type="submit" [disabled]="myForm.form.invalid">Submit</button>
</form>

4. Summary

In this tutorial, we've covered:

  • The creation of template-driven forms
  • The use of two-way data binding
  • The validation of form inputs
  • The handling of form submission

5. Practice Exercises

  1. Exercise: Create a login form with fields for username and password.
  2. Exercise: Add validation to the login form. The username should be required and the password should be at least 8 characters long.
  3. Exercise: Implement a form submission event that logs the form values to the console.

For further practice and to deepen your understanding, try extending the form to include more complex validations or additional fields. You can also explore handling form submission in more detail, such as sending the form data to a server or handling server responses.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Date Difference Calculator

Calculate days between two dates.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help