Creating a Blogging App Using Angular & MongoDB: Login

Angular is a one-stop framework for creating mobile and web apps using the same reusable code. Using Angular, you can divide the whole application into reusable components, which makes it easier to maintain and reuse code.

In this tutorial series, you’ll learn how to get started with creating a web app using Angular with MongoDB as the back end. You’ll be using Node.js for running the server.

Throughout the course of this tutorial, you’ll be building a blogging application using Angular, Node.js, and MongoDB. 

In this tutorial, you’ll see how to get started with setting up the application and creating the Login component.

Getting Started

Let’s get started by installing the Angular CLI.

npm install -g @angular/cli

Once you have installed the Angular CLI, create a project folder called AngularBlogApp

mkdir AngularBlogApp
cd AngularBlogApp

From the project folder, create a new Angular app using the following command:

ng new client

Once you have the client app created, navigate to the project folder and install the required dependencies using Node Package Manager (npm).

cd client
npm install

Start the client server using npm.

npm start

You should have the application running at http://localhost:4200/.

Setting Up the Application

Your Angular web app will have a root component. Create a folder called root inside the src/app folder. Create a file called root.component.html and add the following HTML code:

<h3>
    Root Component
</h3>

Add a file called root.component.ts and add the following code:

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

@Component({
  selector: 'app-root',
  templateUrl: './root.component.html'
})
export class RootComponent {
  
}

Remove the files app.component.html, app.component.ts, app.component.scss, and app.component.spec.ts. You will have only one file called app.module.ts inside the src/app folder.

Import the RootComponent inside the app.module.ts file.

import { RootComponent } from './root/root.component';

Include the RootComponent in the ngModules and bootstrap it.

@NgModule({
  declarations: [
    RootComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [RootComponent]
})

Save the changes and restart the server. You will have the RootComponent displayed when the application loads.

You’ll be using Angular Router for routing in our blogging app. So import routing-related dependencies in a new file called app.routing.ts inside the src/app folder.

import { RouterModule, Routes } from '@angular/router';
import { ModuleWithProviders } from '@angular/core/src/metadata/ng_module';

Define the route path along with the components as shown:

export const AppRoutes: Routes = [
    { path: '', component: LoginComponent }
];

Export the routes to create a module with all route providers.

export const ROUTING: ModuleWithProviders = RouterModule.forRoot(AppRoutes);

Here is how the app.routing.ts file looks:

import { RouterModule, Routes } from '@angular/router';
import { ModuleWithProviders } from '@angular/core/src/metadata/ng_module';

import { LoginComponent } from './login/login.component';

export const AppRoutes: Routes = [
    { path: '', component: LoginComponent }
];

export const ROUTING: ModuleWithProviders = RouterModule.forRoot(AppRoutes);

As seen in the above code, you haven’t yet created the LoginComponent. It’s been added for the sake of clarity.

Import the ROUTING class in the app.module.ts file. 

import { ROUTING } from './app.routing';

Include it in the NgModule imports.

imports: [
    BrowserModule,
    ROUTING,
    FormsModule
]

Place RouterOutlet in the root.component.html page. This where the route’s component gets rendered.

<router-outlet></router-outlet>

Create a folder called login inside the src/app folder. Inside the login folder, create a file called login.component.ts and add the following code:

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

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {

  constructor() {
      
  }

}

Create a file called login.component.html and add the following code:

<h3>
    Login Component
</h3>

Save the above changes and restart the server. As the per the routes defined when the application loads the LoginComponent will get displayed.

Login Component -  Blogging App

Creating the Login Component

You already laid the foundation for the LoginComponent while setting up the application. Let’s create the view for the LoginComponent using Bootstrap.

Download and include the bootstrap CSS style in the assets folder and include the reference in the src/index.html page.

<link rel="stylesheet" type="text/css" href="./assets/bootstrap.min.css">

Place a wrapper around the app-root in the index.html page.

<div class="container">
  	<app-root></app-root>
</div>

Add the following HTML to the login.component.html page.

<form class="form-signin">
     <h2 class="form-signin-heading">Please sign in</h2>
     <label for="inputEmail" class="sr-only">Email address</label>
        <input name="email" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input name="password"  type="password" id="inputPassword" class="form-control" placeholder="Password" required>
        <div class="checkbox">
          <label>
            <input type="checkbox" value="remember-me"> Remember me
          </label>
        </div>
    <button class="btn btn-lg btn-primary btn-block" type="button">Sign in</button>
</form>

Create a file called login.component.css inside the login folder and add the following CSS style.

.form-signin {
  max-width: 330px;
  padding: 15px;
  margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
  margin-bottom: 10px;
}
.form-signin .checkbox {
  font-weight: 400;
}
.form-signin .form-control {
  position: relative;
  box-sizing: border-box;
  height: auto;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

Modify the @Component decorator to include the CSS style.

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

Save the above changes and try loading the application. You will have the LoginComponent displayed with the login view.

Login Screen Angular Blogging App

Creating the Login Service

LoginComponent will need to interact with the database to see if the logged-in user is valid or not. So it will need to make API calls. You’ll keep the database interaction portion in a separate file called login.service.ts.

Create a file called login.service.ts and add the following code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class LoginService {

    constructor(private http: HttpClient){

	}
	
	validateLogin(){
		
	}

}

Import the LoginService in the LoginComponent and add it as a provider in the component decorator. 

import { LoginService } from './login.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [ LoginService ]
})

Add a method called validateLogin in the login.service.ts file which will make the API call. Here is how it looks:

validateLogin(user: User){
	return this.http.post('/api/user/login',{
		username : user.username,
		password : user.password
	})
}

As seen in the above code, it returns an observable which will be subscribed in the login.component.ts file. Here is how the login.service.ts file looks:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../models/user.model';

@Injectable()
export class LoginService {

    constructor(private http: HttpClient){

	}
	
	validateLogin(user: User){
		return this.http.post('/api/user/login',{
			username : user.username,
			password : user.password
		})
	}

}

Implementing User Login Validation

Add the ngModel directive to the input elements in login.component.html.

 <input name="email" [(ngModel)] = "user.username" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
 <input name="password" [(ngModel)] = "user.password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>

Add a click event to the sign in button.

<button class="btn btn-lg btn-primary btn-block" (click)="validateLogin();" type="button">Sign in</button>

Here is how the modified login.component.html looks:

<form class="form-signin">
     <h2 class="form-signin-heading">Please sign in</h2>
     <label for="inputEmail" class="sr-only">Email address</label>
        <input name="email" [(ngModel)] = "user.username" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input name="password" [(ngModel)] = "user.password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
        <div class="checkbox">
          <label>
            <input type="checkbox" value="remember-me"> Remember me
          </label>
        </div>
    <button class="btn btn-lg btn-primary btn-block" (click)="validateLogin();" type="button">Sign in</button>
</form>

Define and initialize the user variable in the login.component.ts file.

public user : User;

constructor(private loginService: LoginService) {
  this.user = new User();
}

The User model has been defined in the src/app/models folder. Here is how it looks:

export class User {
    constructor(){
		this.username = '';
		this.password = '';
	}
	public username;
	public password;
}

Define a method called validateLogin which will be called on button click. Here is how the method looks:

validateLogin() {
  if(this.user.username && this.user.password) {
  	this.loginService.validateLogin(this.user).subscribe(result => {
    console.log('result is ', result);
  }, error => {
    console.log('error is ', error);
  });
  } else {
  	alert('enter user name and password');
  }
}

When both username and password have been entered, the validateLogin method subscribes to the LoginService method to validate the user login.

Here is how the login.component.ts file looks:

import { Component } from '@angular/core';
import { LoginService } from './login.service';
import { User } from '../models/user.model';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [ LoginService ]
})
export class LoginComponent {

  public user : User;

  constructor(private loginService: LoginService) {
      this.user = new User();
  }

  validateLogin() {
  	if(this.user.username && this.user.password) {
  		this.loginService.validateLogin(this.user).subscribe(result => {
        console.log('result is ', result);
      }, error => {
        console.log('error is ', error);
      });
  	} else {
  		alert('enter user name and password');
  	}
  }

}

Wrapping It Up

In this part of the Angular blogging app tutorial series, you saw how to get started with creating a web app using Angular. You created the basic structure of the Angular app and created the LoginComponent which will enable the user to validate the username and password. 

In the next part of the tutorial series, you’ll write the REST API for user login validation and create the home component.

Source code from this tutorial is available on GitHub.

Do let us know your thoughts and suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *