<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ template-driven-forms - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ template-driven-forms - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 23 Jun 2026 21:16:17 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/template-driven-forms/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Validate Angular Template-Driven Forms ]]>
                </title>
                <description>
                    <![CDATA[ By Ankit Sharma Introduction In this article, we will learn about validations in Angular template-driven forms. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-validate-angular-template-driven-forms/</link>
                <guid isPermaLink="false">66d45dcb55db48792eed3f25</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ template-driven-forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 22 Dec 2019 08:18:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9e88740569d1a4ca3da3.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ankit Sharma</p>
<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>In this article, we will learn about validations in Angular template-driven forms. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will also implement some custom validations for the template-driven form. </p>
<p>We will consider the following custom validations for this demo:</p>
<ul>
<li>Checking for user name availability</li>
<li>Password pattern validation</li>
<li>Matching the password entered in two different fields</li>
</ul>
<p>Take a look at the application in action.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/TemplateFormValidation.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<ul>
<li>Install Visual Studio code from <a target="_blank" href="https://code.visualstudio.com/">here</a></li>
<li>Install the latest version of Angular CLI from <a target="_blank" href="https://cli.angular.io/">here</a></li>
<li>Install the latest LTS version of Node.js from <a target="_blank" href="https://nodejs.org/en/">here</a></li>
</ul>
<h2 id="heading-source-code"><strong>Source Code</strong></h2>
<p>You can get the source code from <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation">GitHub</a>.</p>
<h2 id="heading-create-the-angular-app"><strong>Create the Angular app</strong></h2>
<p>Navigate to the folder where you want to create your project file. Open a command window and run the command shown below:</p>
<pre><code>ng <span class="hljs-keyword">new</span> angular-forms-validation --routing=<span class="hljs-literal">false</span> --style=scss
</code></pre><p>We are specifying the command to create a new Angular application. The option to create the routing module is set to false and style files extension is set to SCSS. This command will create the Angular project with the name angular-forms-validation.</p>
<p>Change directories to the new project and open the project in VS Code using the set of commands below:</p>
<pre><code>cd angular-forms-validation
code .
</code></pre><h2 id="heading-install-bootstrap">Install Bootstrap</h2>
<p>Run the following command to install Bootstrap:</p>
<pre><code>npm install bootstrap --save
</code></pre><p>Add the following import definition in the <code>styles.scss</code> file:</p>
<pre><code>@<span class="hljs-keyword">import</span> <span class="hljs-string">"~bootstrap/dist/css/bootstrap.css"</span>;
</code></pre><h2 id="heading-create-the-validation-service">Create the validation service</h2>
<p>Run the following command to create a new service:</p>
<pre><code>ng g s services\customvalidation
</code></pre><p>This command will create a folder named services that has two files inside it – <code>customvalidation.service.ts</code> and <code>customvalidation.service.spec.ts</code>. Open <code>customvalidation.service.ts</code> and put the following code inside it:</p>
<pre><code><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { ValidatorFn, AbstractControl } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { FormGroup } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

@Injectable({
  <span class="hljs-attr">providedIn</span>: <span class="hljs-string">'root'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomvalidationService</span> </span>{

  patternValidator(): ValidatorFn {
    <span class="hljs-keyword">return</span> (control: AbstractControl): { [key: string]: any } =&gt; {
      <span class="hljs-keyword">if</span> (!control.value) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }
      <span class="hljs-keyword">const</span> regex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$'</span>);
      <span class="hljs-keyword">const</span> valid = regex.test(control.value);
      <span class="hljs-keyword">return</span> valid ? <span class="hljs-literal">null</span> : { <span class="hljs-attr">invalidPassword</span>: <span class="hljs-literal">true</span> };
    };
  }

  MatchPassword(password: string, <span class="hljs-attr">confirmPassword</span>: string) {
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">formGroup: FormGroup</span>) =&gt;</span> {
      <span class="hljs-keyword">const</span> passwordControl = formGroup.controls[password];
      <span class="hljs-keyword">const</span> confirmPasswordControl = formGroup.controls[confirmPassword];

      <span class="hljs-keyword">if</span> (!passwordControl || !confirmPasswordControl) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }

      <span class="hljs-keyword">if</span> (confirmPasswordControl.errors &amp;&amp; !confirmPasswordControl.errors.passwordMismatch) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }

      <span class="hljs-keyword">if</span> (passwordControl.value !== confirmPasswordControl.value) {
        confirmPasswordControl.setErrors({ <span class="hljs-attr">passwordMismatch</span>: <span class="hljs-literal">true</span> });
      } <span class="hljs-keyword">else</span> {
        confirmPasswordControl.setErrors(<span class="hljs-literal">null</span>);
      }
    }
  }

  userNameValidator(userControl: AbstractControl) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.validateUserName(userControl.value)) {
          resolve({ <span class="hljs-attr">userNameNotAvailable</span>: <span class="hljs-literal">true</span> });
        } <span class="hljs-keyword">else</span> {
          resolve(<span class="hljs-literal">null</span>);
        }
      }, <span class="hljs-number">1000</span>);
    });
  }

  validateUserName(userName: string) {
    <span class="hljs-keyword">const</span> UserList = [<span class="hljs-string">'ankit'</span>, <span class="hljs-string">'admin'</span>, <span class="hljs-string">'user'</span>, <span class="hljs-string">'superuser'</span>];
    <span class="hljs-keyword">return</span> (UserList.indexOf(userName) &gt; <span class="hljs-number">-1</span>);
  }
}
</code></pre><p>The method <code>patternValidator</code> is used to validate the password pattern in our form. The parameter for this method is of type <code>AbstractControl</code> which is a base class for the <code>FormControl</code>. </p>
<p>We will use a regular expression to validate the password. This regular expression will check for the following four conditions in the password:</p>
<ul>
<li>The password should be a minimum of eight characters long</li>
<li>It should have at least one lower case letter</li>
<li>It should have at least one upper case letter</li>
<li>It should have at least one number</li>
</ul>
<p>If the password fails the regex check, we will set the <code>invalidPassword</code> property to true.</p>
<p>The method <code>MatchPassword</code> is used to compare the passwords in two fields. This method will accept two parameters of type string. These parameters represent the name of the fields to be matched. We will get the <code>FormControl</code> for these two fields and then match the values in them. If the values do not match, we will set the <code>passwordMismatch</code> property to true.</p>
<p>The method <code>userNameValidator</code> is used to verify if the username is already taken or not. This method will accept a parameter of type <code>AbstractControl</code>. </p>
<p>We will check if the value of this field is present in a static array, UserList. If the value entered by the user is already present, we will set the <code>userNameNotAvailable</code> property to true. </p>
<p>We are using the setTimeout function to invoke this check every two seconds. This will ensure that the error will be thrown after two seconds from the time the user stops typing in the field.</p>
<p>For the sake of simplicity of this article, we are using a static array to search for the availability of user names. Ideally, it should be a service call to the server to search for the value in a database.</p>
<h2 id="heading-create-the-user-model">Create the User model</h2>
<p>Create a new folder called models inside the <code>src/app</code> folder. Add a new file called <code>user.ts</code> inside the models folder. Put the following code in the <code>user.ts</code> file.</p>
<pre><code><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    public name: string;
    public email: string;
    public username: string;
    public password: string;
    public confirmPassword: string;
}
</code></pre><h2 id="heading-create-custom-directives">Create custom directives</h2>
<p>We will create custom directives to implement custom validators for template-driven forms.</p>
<p>Run the command shown below to create the <code>passwordPattern</code> directive:</p>
<pre><code>ng g d directives\passwordPattern
</code></pre><p>This command will create a folder named directives that has two files inside it – <code>passwordPattern.directive.ts</code> and <code>passwordPattern.directive.spec.ts</code>. Open <code>passwordPattern.directive.ts</code> and put the following code inside it.</p>
<pre><code><span class="hljs-keyword">import</span> { Directive } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { NG_VALIDATORS, Validator, AbstractControl } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { CustomvalidationService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../services/customvalidation.service'</span>;

@Directive({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'[appPasswordPattern]'</span>,
  <span class="hljs-attr">providers</span>: [{ <span class="hljs-attr">provide</span>: NG_VALIDATORS, <span class="hljs-attr">useExisting</span>: PasswordPatternDirective, <span class="hljs-attr">multi</span>: <span class="hljs-literal">true</span> }]
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PasswordPatternDirective</span> <span class="hljs-title">implements</span> <span class="hljs-title">Validator</span> </span>{

  <span class="hljs-keyword">constructor</span>(private customValidator: CustomvalidationService) { }

  validate(control: AbstractControl): { [key: string]: any } | <span class="hljs-literal">null</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.customValidator.patternValidator()(control);
  }
}
</code></pre><p>This directive is used to validate the password pattern. We will implement the Validator interface on the class <code>PasswordPatternDirective</code>. We will override the validate method which accepts a parameter of type <code>AbstractControl</code>, that is the control we want to validate. We will then invoke the <code>patternValidator</code> method from the service.</p>
<p>Run the command shown below to create the <code>matchPassword</code> directive:</p>
<pre><code>ng g d directives\matchPassword
</code></pre><p>Open <code>matchPassword.directive.ts</code> and put the following code inside it:</p>
<pre><code><span class="hljs-keyword">import</span> { Directive, Input } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { NG_VALIDATORS, Validator, ValidationErrors, FormGroup } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { CustomvalidationService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../services/customvalidation.service'</span>;

@Directive({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'[appMatchPassword]'</span>,
  <span class="hljs-attr">providers</span>: [{ <span class="hljs-attr">provide</span>: NG_VALIDATORS, <span class="hljs-attr">useExisting</span>: MatchPasswordDirective, <span class="hljs-attr">multi</span>: <span class="hljs-literal">true</span> }]
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MatchPasswordDirective</span> <span class="hljs-title">implements</span> <span class="hljs-title">Validator</span> </span>{
  @Input(<span class="hljs-string">'appMatchPassword'</span>) MatchPassword: string[] = [];

  <span class="hljs-keyword">constructor</span>(private customValidator: CustomvalidationService) { }

  validate(formGroup: FormGroup): ValidationErrors {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.customValidator.MatchPassword(<span class="hljs-built_in">this</span>.MatchPassword[<span class="hljs-number">0</span>], <span class="hljs-built_in">this</span>.MatchPassword[<span class="hljs-number">1</span>])(formGroup);
  }
}
</code></pre><p>This directive is used to validate if the passwords entered in two fields are matching or not. This directive will accept an input of the type string array, which contains the fields to match. We will override the validate method and pass the parameter of type <code>FormGroup</code>. We will then invoke the <code>MatchPassword</code> method from the service. </p>
<p>Run the command shown below to create the <code>validateUserName</code> directive:</p>
<pre><code>ng g d directives\validateUserName
</code></pre><p>Open <code>validateUserName.directive.ts</code> and put the following code inside it:</p>
<pre><code><span class="hljs-keyword">import</span> { Directive, forwardRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { Validator, AbstractControl, NG_ASYNC_VALIDATORS } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { CustomvalidationService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../services/customvalidation.service'</span>;
<span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;

@Directive({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'[appValidateUserName]'</span>,
  <span class="hljs-attr">providers</span>: [{ <span class="hljs-attr">provide</span>: NG_ASYNC_VALIDATORS, <span class="hljs-attr">useExisting</span>: forwardRef(<span class="hljs-function">() =&gt;</span> ValidateUserNameDirective), <span class="hljs-attr">multi</span>: <span class="hljs-literal">true</span> }]

})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ValidateUserNameDirective</span> <span class="hljs-title">implements</span> <span class="hljs-title">Validator</span> </span>{

  <span class="hljs-keyword">constructor</span>(private customValidator: CustomvalidationService) { }

  validate(control: AbstractControl): <span class="hljs-built_in">Promise</span>&lt;{ [key: string]: any }&gt; | Observable&lt;{ [key: string]: any }&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.customValidator.userNameValidator(control);
  }
}
</code></pre><p>This directive is used to validate the availability of the user name. We will override the validate method and pass the parameter of type <code>AbstractControl</code>. We will then invoke the <code>userNameValidator</code> method from the service. This method will return a promise.</p>
<h2 id="heading-create-the-template-driven-form-component">Create the template-driven form component</h2>
<p>Run the command shown below to create the template-driven-form component:</p>
<pre><code>ng g c template-driven-form
</code></pre><p>Open <code>template-driven-form.component.ts</code> and put the following code in it:</p>
<pre><code><span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { User } <span class="hljs-keyword">from</span> <span class="hljs-string">'../models/user'</span>;

@Component({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'app-template-driven-form'</span>,
  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./template-driven-form.component.html'</span>,
  <span class="hljs-attr">styleUrls</span>: [<span class="hljs-string">'./template-driven-form.component.scss'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TemplateDrivenFormComponent</span> </span>{

  userModal = <span class="hljs-keyword">new</span> User();

  <span class="hljs-keyword">constructor</span>() { }

  onSubmit() {
    alert(<span class="hljs-string">'Form Submitted succesfully!!!\n Check the values in browser console.'</span>);
    <span class="hljs-built_in">console</span>.table(<span class="hljs-built_in">this</span>.userModal);
  }
}
</code></pre><p>We have created an object <code>userModal</code> of type User. We will bind the form fields with the property of this object. The <code>onSubmit</code> method will show the success message on the screen and print the contents of the form to the console.</p>
<p>Open <code>template-driven-form.component.html</code> and put the following code in it:</p>
<pre><code>&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"container"</span>&gt;
    &lt;div class="row"&gt;
        &lt;div class="col-md-8 mx-auto"&gt;
            &lt;div class="card"&gt;
                &lt;div class="card-header"&gt;
                    &lt;h3&gt;Angular Template-driven Form&lt;/h3&gt;
                &lt;/div&gt;
                &lt;div class="card-body"&gt;
                    &lt;form class="form" #registerForm="ngForm" [appMatchPassword]="['password', 'confirmPassword']"
                        (ngSubmit)="registerForm.form.valid &amp;&amp; onSubmit()" novalidate&gt;
                        &lt;div class=" form-group"&gt;
                            &lt;label&gt;Name&lt;/label&gt;
                            &lt;input type="text" class="form-control" [(ngModel)]="userModal.name" name="name"
                                #name="ngModel" required&gt;
                            &lt;span class="text-danger"
                                *ngIf="(name.touched || registerForm.submitted) &amp;&amp; name.errors?.required"&gt;
                                Name is required
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;label&gt;Email&lt;/label&gt;
                            &lt;input type="text" class="form-control" [(ngModel)]="userModal.email" name="email"
                                #email="ngModel" required email&gt;
                            &lt;span class="text-danger"
                                *ngIf="(email.touched || registerForm.submitted) &amp;&amp; email.errors?.required"&gt;
                                Email is required
                            &lt;/span&gt;
                            &lt;span class="text-danger" *ngIf="email.touched &amp;&amp; email.errors?.email"&gt;
                                Enter a valid email address
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;label&gt;User Name&lt;/label&gt;
                            &lt;input type="text" class="form-control" [(ngModel)]="userModal.username" name="username"
                                #username="ngModel" appValidateUserName required&gt;
                            &lt;span class="text-danger"
                                *ngIf="(username.touched || registerForm.submitted) &amp;&amp; username.errors?.required"&gt;
                                User Name is required
                            &lt;/span&gt;
                            &lt;span class="text-danger" *ngIf="username.touched &amp;&amp; username.errors?.userNameNotAvailable"&gt;
                                User Name not available
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;label&gt;Password&lt;/label&gt;
                            &lt;input type="password" class="form-control" [(ngModel)]="userModal.password" name="password"
                                #password="ngModel" appPasswordPattern required&gt;
                            &lt;span class="text-danger"
                                *ngIf="(password.touched || registerForm.submitted) &amp;&amp; password.errors?.required"&gt;
                                Password is required
                            &lt;/span&gt;
                            &lt;span class="text-danger" *ngIf="password.touched &amp;&amp; password.errors?.invalidPassword"&gt;
                                Password should have minimum 8 characters, at least 1 uppercase letter, 1 lowercase
                                letter and 1 number
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;label&gt;Confirm Password&lt;/label&gt;
                            &lt;input type="password" class="form-control" [(ngModel)]="userModal.confirmPassword"
                                name="confirmPassword" #confirmPassword="ngModel" required&gt;
                            &lt;span class="text-danger"
                                *ngIf="(confirmPassword.touched || registerForm.submitted) &amp;&amp; confirmPassword.errors?.required"&gt;
                                Confirm Password is required
                            &lt;/span&gt;
                            &lt;span class="text-danger"
                                *ngIf="confirmPassword.touched &amp;&amp; confirmPassword.errors?.passwordMismatch"&gt;
                                Passwords doesnot match
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;button type="submit" class="btn btn-success"&gt;Register&lt;/button&gt;
                        &lt;/div&gt;
                    &lt;/form&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre><p>We will create a template-driven form and use the Bootstrap card for styling. The card header will contain a title whereas the card body will have the form fields. </p>
<p>We will use the <code>appMatchPassword</code> directive on our form and pass the password and <code>confirmPassword</code> fields for validation. The <code>ngModel</code> property is used to bind the form control to the model. </p>
<p>For validating the user name availability we will use the <code>appValidateUserName</code> directive on the username field. Similarly, we will use the <code>appPasswordPattern</code> directive on the password field to validate the password pattern. </p>
<p>We will check for the errors in the form controls and then display the appropriate validation error message on the screen.</p>
<h2 id="heading-create-the-nav-bar-component">Create the nav-bar component</h2>
<p>Run the command shown below to create the nav-bar component:</p>
<pre><code>ng g c nav-bar
</code></pre><p>Open <code>nav-bar.component.html</code> and put the following code in it:</p>
<pre><code>&lt;nav <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"navbar navbar-expand-sm navbar-dark bg-dark fixed-top"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-brand"</span> [<span class="hljs-attr">routerLink</span>]=<span class="hljs-string">'["/"]'</span>&gt;</span>Form Validation Demo<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"collapse navbar-collapse"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-nav mr-auto"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-link"</span> [<span class="hljs-attr">routerLink</span>]=<span class="hljs-string">'["/template-form"]'</span>&gt;</span>Template Form<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
&lt;/nav&gt;
</code></pre><p>Here we are adding the navigation link to the template-driven form component.</p>
<h2 id="heading-update-the-app-component">Update the app component</h2>
<p>Open the <code>app.component.html</code> file and put the following code in it:</p>
<pre><code>&lt;app-nav-bar&gt;&lt;/app-nav-bar&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">router-outlet</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">router-outlet</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre><h2 id="heading-update-the-app-module">Update the App module</h2>
<p>We will import the forms module and also set up the routing for our application in the app module. Add the following code in the <code>app.module.ts</code> file. You can refer to <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation/blob/master/src/app/app.module.ts">GitHub</a> for the complete source code of this file:</p>
<pre><code><span class="hljs-keyword">import</span> { RouterModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/router'</span>;
<span class="hljs-keyword">import</span> { FormsModule } <span class="hljs-keyword">from</span>  <span class="hljs-string">'@angular/forms'</span>;

@NgModule({
  ...    
  imports: [
    ...
    FormsModule,
    RouterModule.forRoot([
      { <span class="hljs-attr">path</span>: <span class="hljs-string">''</span>, <span class="hljs-attr">component</span>: TemplateDrivenFormComponent },
      { <span class="hljs-attr">path</span>: <span class="hljs-string">'template-form'</span>, <span class="hljs-attr">component</span>: TemplateDrivenFormComponent }
    ]),
  ],
})
</code></pre><h2 id="heading-execution-demo">Execution demo</h2>
<p>Use the following command to start the webserver:</p>
<pre><code>ng serve -o
</code></pre><p>This command will launch the application in your default browser at <code>http://localhost:4200/</code>. You can perform all the form validations which we have discussed here. </p>
<p>This application is also hosted at <a target="_blank" href="https://ng-forms-validation.herokuapp.com/">https://ng-forms-validation.herokuapp.com/</a>. Navigate to the link and play around with it for a better understanding.</p>
<h2 id="heading-summary">Summary</h2>
<p>We have created a sample user registration form using the template-driven form approach in Angular. We have implemented the inbuilt validations as well as custom validations to the form. The Bootstrap library is used to style the form. </p>
<p>Get the source code from <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation">GitHub</a> and play around with it for a better understanding.</p>
<h2 id="heading-see-also">See Also</h2>
<ul>
<li><a target="_blank" href="https://ankitsharmablogs.com/reactive-form-validation-in-angular/">Reactive Form Validation In Angular</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/localization-in-angular-using-i18n-tools/">Localization In Angular Using i18n Tools</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/policy-based-authorization-in-angular-using-jwt/">Policy-Based Authorization In Angular Using JWT</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/asp-net-core-using-highcharts-with-angular-5/">ASP.NET Core – Using Highcharts With Angular 5</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/asp-net-core-crud-using-angular-and-entity-framework-core/">ASP.NET Core – CRUD Using Angular And Entity Framework Core</a></li>
</ul>
<p>You can find this post <a target="_blank" href="https://ankitsharmablogs.com/template-driven-form-validation-in-angular/">Template-Driven Form Validation In Angular</a> and others like it on <a target="_blank" href="https://ankitsharmablogs.com/">Ankit Sharma's Blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
