Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit)

Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit)

In this post we will give you information about Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit). Hear we will give you detail about Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit)And how to use it also give you demo for it if it is necessary.

In this tutorial, we’ll learn to use the template-driven approach in Angular 9/8 to work with forms. We’ll learn about the NgForm, ngModel and ngSubmit directives which are the essential concepts in template-based forms and how to create an authentication system with Node and Express.js

Note: This tutorial also works with Angular 7 and 8.

Why Using Forms in Angular 9?

Forms and authentication are common features in every Angular app or generally any web application. A form is used to collect and submit information to web servers which will usually be persisted in a database while authentication is used to verify the identity of users before allowing them to access protected resources on the server.

Creating Forms in Angular 9 by Example

In this tutorial, you will create an Angular 9 application with two forms that send user information to a RESTful server to save it in the database (registration) and then allow users to authenticate themselves. You’ll create a login and register components with two forms to register and login users.

Since Angular is only for the front-end, we’ll also need a back-end server. We’ll quickly create a server with Node and Express.js that exposes two endpoints for registering and authenticating users.


You will need a few requirements for this tutorial:

  • Node.js and NPM. head over to their official website and grab the binaries for your system.
  • The latest version of Angular CLI v7 installed (npm install -g @angular/cli).

Creating and Setting up The Node and Express.js Authentication Server

Let’s get started with our first step. Open a terminal, create a folder for both the frontend and backend applications:

$ mkdir angular-auth-forms-demo

Next, navigate inside it and create a backend folder:

$ cd angular-auth-forms-demo$ mkdir backend$ cd backend

Next, create a Node.js module by running the following command:

$ npm init -y

This will create package.json file with default values which you can change later if you want. Now, run the following commands to install the dependencies:

$ npm install --save express body-parser sqlite3 bcryptjs jsonwebtoken cors

This will install express.js and a bunch of other modules such as sqlite3 for working with a SQLite database and jsonwebtoken for working witj JSON web tokens or JWTs.

Note: As the time of this writing the following pages and versions will be installed:cors v2.8.5body-parser v1.18.3sqlite3 v4.0.6bcryptjs v2.4.3express v4.16.4jsonwebtoken v8.4.0

Next, create an index.js file and add:

"use strict";constexpress=require('express');constbodyParser=require('body-parser');constcors=require('cors')constsqlite3=require('sqlite3').verbose();constjwt=require('jsonwebtoken');constbcrypt=require('bcryptjs');constSECRET_KEY="secretkey23456";constapp=express();constrouter=express.Router();app.use(cors())router.use(bodyParser.urlencoded({extended:false}));router.use(bodyParser.json());constdatabase=newsqlite3.Database("./my.db");constcreateUsersTable=()=>{constsqlQuery='CREATETABLEIFNOTEXISTSusers(idintegerPRIMARYKEY,nametext,emailtextUNIQUE,passwordtext)';;}constfindUserByEmail=(email,cb)=>{returndatabase.get('SELECT*FROMusersWHEREemail=?',[email],(err,row)=>{cb(err,row)});}constcreateUser=(user,cb)=>{'INSERT INTO users (name, email, password) VALUES (?,?,?)',user,(err)=>{cb(err)});}createUsersTable();router.get('/',(req,res)=>{res.status(200).send('This is an authentication server');});'/register',(req,res)=>{;;console.log(req.body);constpassword=bcrypt.hashSync(req.body.password);createUser([name,email,password],(err)=>{if(err)returnres.status(500).send("Server error!");findUserByEmail(email,(err,user)=>{if(err)returnres.status(500).send('Server error!');constexpiresIn=24*60*60;constaccessToken=jwt.sign({},SECRET_KEY,{expiresIn:expiresIn});res.status(200).send({"user":user,"access_token":accessToken,"expires_in":expiresIn});});});});'/login',(req,res)=>{;constpassword=req.body.password;findUserByEmail(email,(err,user)=>{if(err)returnres.status(500).send('Server error!');if(!user)returnres.status(404).send('User not found!');constresult=bcrypt.compareSync(password,user.password);if(!result)returnres.status(401).send('Password not valid!');constexpiresIn=24*60*60;constaccessToken=jwt.sign({},SECRET_KEY,{expiresIn:expiresIn});res.status(200).send({"user":user,"access_token":accessToken,"expires_in":expiresIn});});});app.use(router);constport=process.env.PORT||3000;constserver=app.listen(port,()=>{console.log('Server listening at http://localhost:'+port);});

We are not going to explain this code here because it’s thoroughly detailed in a previous tutorial. If you want to understand how the code above works, you can first read Node Express JWT Authentication — jsonwebtoken and bcryptjs.

Next, add a start script in package.json:

"scripts":{"start":"node index.js"},

This script will allow you to run your Express.js server from the terminal using this command:

$ npm start

Your server will be served from http://localhost:3000. Since our server exposes a GET route, you can visit it with your web browser. You should see a blank page with the This is an authentication server message. That means your authentication server is working!

You can also use a REST API client like Postman or cURL to send POST requests to the /register and /login endpoints to create in the SQLite database and authenticate users before we create the Angular 9 UI.

For example, this is how you send a POST request with cURL:

 curl -H "Content-Type: application/json" -d '{"email":"","name":"user", "password":"password"}' http://localhost:3000/register

You can then send another POST request to authenticate the user you just created:

 curl -H "Content-Type: application/json" -d '{"email":"", "password":"password"}' http://localhost:3000/login

If the POST requests are successful you should get a JSON object with your user information, the access token and the expiration date otherwise you will get an error with a status code.

That’s it for the server part! You should leave this terminal open with your server running and let’s start creating the Angular 9 application.

Creating the Angular 9 Application

Open a new terminal and navigate to your project’s folder then run the following command to generate the frontend project using Angular CLI 7:

$ ng new frontend

You will be propmted if Would you like to add Angular routing? Enter y. And Which stylesheet format would you like to use? Select CSS.

You can start the development server using:

$ ng serve

You can access your application from http://localhost:4200 in your preferred web browser. You will be presented with the following page:

Creating an Angular 9 Module

We’ll add the code for this tutorial in its own Angular module which will encapsulate authentication. Head back to your terminal and run the following command:

$ ng generate module auth --routing

This will create a module called auth with routing (thanks to the --routing switch). Two src/app/auth/auth-routing.module.ts (the routing module for the auth module) and src/app/auth/auth.module.ts files will be created.

Generating Angular 9 Components

Next, we’ll generate two components for the login and registration inside the auth module. In your terminal, run the following command:

$ ng generate component auth/register$ ng generate component auth/login

You see that we prefixed the names of the components with the auth/ path which tells the CLI to generate them inside the auth module.

The components will be automatically imported and declared in the auth module. This is the content of the src/app/auth/auth.module.ts file:


Adding Angular Routing

The next step is to add routing between the different components of our application. Open the src/app/auth/auth-routing.module.ts file and update as follows:


We first import the RegisterComponent and LoginComponent components from their corresponding paths and add two routes in the routes array which is passed to Router with the forChild() method.

Since this is a child module we also need to add a route in the root routing module of the application so open the src/app/app-routing.module.ts file and add the following route to the routes array that’s passed to the forRoot() method:


We use the loadChildren property of the route which takes the path of the auth module.

Since we use the auth path, all components of the auth module will be available under the /auth path i.e the /auth/register and /auth/login routes.

Styling the UI

For styling the UI we’ll be inspired from this codepen.

Now that we have added routing, let’s build the UI of our application. Let’s start with main application component where the router outlet exists i.e the shell of the application. Open the src/app/app.component.html, remove everything except the router outlet:


Open the src/styles.css file and add:


Setting up Angular Forms

Angular provides two ways for working with forms, the template-based forms and reactive forms. In this example, we’ll be using template-based forms by including the FormsModule and by using directives such ngModel for data binding.

Open the src/app/auth/auth.module.ts file and import the FormsModule then add it in the imports array of the module:


Creating the Registration Form: Using Template-based Forms with the ngModel, ngForm and ngSubmit Directives

In this section, we’ll use Angular directives such as ngModel, ngForm and ngSubmit to create a template-based form for registering users.

Open the src/app/auth/register/register.component.html file and add an HTML form for submitting the name, email and password of the user:

<divclass="container"><divclass="logo">Create a new account!</div><divclass="register-item"><form#myform="ngForm"(ngSubmit)="register(myform)"class="form form-register"><divclass="form-field"><labelclass="user"for="register-username"><spanclass="hidden">Name</span></label><inputname="name"id="register-username"type="email"class="form-input"placeholder="Name"ngModelrequired></div><divclass="form-field"><labelclass="user"for="register-email"><spanclass="hidden">Email</span></label><inputname="email"id="register-email"type="email"class="form-input"placeholder="Email"ngModelrequired></div><divclass="form-field"><labelclass="lock"for="register-password"><spanclass="hidden">Password</span></label><inputname="password"id="register-password"type="password"class="form-input"placeholder="Password"ngModelrequired></div><divclass="form-field"><inputtype="submit"value="Register"></div></form></div></div>
  • For each input control, we use the ngModel directive by itself to register the control as a child of the form.
  • For each input, we add a name attribute to the input control. This is required when using template-based forms and the ngModel directive.
  • We declare a template variable for the form using the #myform="ngForm" syntax. The variable myform becomes a reference to the NgForm instance which contains all the controls of the form.

This how Angular docs describes the NgModel:

It creates a [FormControl]( instance from a domain model and binds it to a form control element.The FormControl instance tracks the value, user interaction, and validation status of the control and keeps the view synced with the model. If used within a parent form, the directive also registers itself with the form as a child control.This directive is used by itself or as part of a larger form. Use the [ngModel]( selector to activate it.

For the NgForm directive:

It creates a top-level [FormGroup]( instance and binds it to a form to track aggregate form value and validation status.

As soon as you import the [FormsModule](, this directive becomes active by default on all <form> tags. You don’t need to add a special selector.

You optionally export the directive into a local template variable using [ngForm]( as the key (ex: #myForm="[ngForm](").

Next, you need to define the register(myform) method that you passed in to the ngSubmit event of the form. Open the src/app/auth/register/register.component.ts file and add:


We listen to the form ngSubmit event so when the user makes a form submission we execute the register(form) method which takes a reference to the NgForm instance that was submitted.

We use the value attribute of NgForm to read the values of the form.

Now, if you fill your form and click on the register button you should see the values of the form printed on your browser’s console as a JSON object.

Check out how we submit the form content to the Express.js authentication server with HttpClient POST request in this tutorial: Using Angular HttpClient with Node & Express.js — Example POST Request.

Open the src/app/auth/register/register.component.css file and add the following styles:

Hope this code and post will helped you for implement Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit). if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US