This article shows how to create a Template-driven Angular form with email validation.

1. Add required Angular modules into app.module

Import FormsModule & BrowserModule in app.module.ts

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

import { AppComponent }  from './app.component';

  imports: [
  declarations: [
  bootstrap: [ AppComponent ]
export class AppModule { }

2. Create a HTML input element

Create a new HTML file which is correspond to the templateUrl in the Component class.

Then in the HTML file, create a HTML input element.
Add attributes as followings:
1. required
2. minlength="3"
3. maxlength="20"
4. pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}"

app/app.component.html (Part 1)
        ngModel name="email" 
        aria-describedby="emailHelp" placeholder="Enter email">

3. Create Bootstrap Alert Message Box

Now, create alert messages for specific errors.

For example, if user enters invalid number of characters, then display a specific error message to indicate that the characters should not exceed or less than a number of characters.

app/app.component.html (Part 2)
<div class="alert alert-danger" role="alert" *ngIf="email.touched && !email.valid">
    <div *ngIf="email.errors.minlength">Email cannot be less than 3 characters</div>
    <div *ngIf="email.errors.required">Email is required</div>
    <div *ngIf="email.errors.maxlength">Email cannot be more than 20 characters</div>
    <div *ngIf="email.errors.pattern">Email must be an email pattern</div>

The trick to display correspond message to a specific error is to use *ngIf, with condition.

E.g. email.errors.pattern, this means, if user entered value’s pattern is invalid. email in this case, is the value of email in #email="ngModel" which is also known as template reference.

4. Create style for input elements

Angular automatically add a class i.e .ng-invalid into the element which has error. Therefore, in order to highlight the input element by showing red color in the text-box’s border, create a style of .ng-invalid. Example can be found in app.component.css

Last modified: December 29, 2017