Creating and validating a template-driven form to an Angular application

Rodrigo Kamada
2 min readNov 22, 2021

Introduction

Angular is a development platform for building WEB, mobile and desktop applications using HTML, CSS and TypeScript (JavaScript). Currently, Angular is at version 14 and Google is the main maintainer of the project.

Form validation enables the quality, accuracy, and integrity of the user input data. It’s possible to validate a form in Angular in two ways, one with reactive forms (using functions in the component class) and the other with template-driven forms (using attributes in the HTML) and we will use the template-driven forms way.

Prerequisites

Before you start, you need to install and configure the tools:

Getting started

Create the Angular application

1. Let’s create the application with the Angular base structure using the @angular/cli with the route file and the SCSS style format.

2. Install and configure the Bootstrap CSS framework. Do steps 2 and 3 of the post Adding the Bootstrap CSS framework to an Angular application.

3. Let’s create a custom validator for the email field. Create the EmailValidatorDirective directive.

4. Change the src/app/email-validator.directive.ts file. Create the emailValidator function and the EmailValidatorDirective class as below.

5. Change the src/app/app.component.ts file. Import the NgForm service, create the IUser interface and create the validate function as below.

6. Change the src/app/app.component.html file. Add the form as below.

7. Change the src/app/app.module.ts file. Import the FormsModule module and the EmailValidatorDirective directive as below.

8. Run the application with the command below.

9. Ready! Access the URL http://localhost:4200/ and check if the application is working. See the application working on GitHub Pages and Stackblitz.

The application repository is available at https://github.com/rodrigokamada/angular-template-driven-form-validation.

This tutorial was posted on my blog in portuguese.

--

--

Rodrigo Kamada

👨‍💻 Software Developer | ✍️ Technical Content Creator | 🤝 Open Source Contributor | 🎙️ Speaker | 👨‍🏫 Mentor | 🙌 Ambassador | ☁️ AWS Community Builder