1. Code
  2. JavaScript
  3. Angular

Creating a Blogging App Using Angular & MongoDB: Login

Scroll to top
This post is part of a series called Creating a Blogging App Using Angular & MongoDB.
Creating a Blogging App Using Angular & MongoDB: Home

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.

1
npm install -g @angular/cli

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

1
mkdir AngularBlogApp
2
cd AngularBlogApp

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

1
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).

1
cd client
2
npm install

Start the client server using npm.

1
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:

1
<h3>
2
    Root Component
3
</h3>

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

1
import { Component } from '@angular/core';
2
3
@Component({
4
  selector: 'app-root',
5
  templateUrl: './root.component.html'
6
})
7
export class RootComponent {
8
  
9
}

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.

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

Include the RootComponent in the ngModules and bootstrap it.

1
@NgModule({
2
  declarations: [
3
    RootComponent
4
  ],
5
  imports: [
6
    BrowserModule,
7
    FormsModule
8
  ],
9
  providers: [],
10
  bootstrap: [RootComponent]
11
})

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.

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

Define the route path along with the components as shown:

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

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

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

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

1
import { RouterModule, Routes } from '@angular/router';
2
import { ModuleWithProviders } from '@angular/core/src/metadata/ng_module';
3
4
import { LoginComponent } from './login/login.component';
5
6
export const AppRoutes: Routes = [
7
    { path: '', component: LoginComponent }
8
];
9
10
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. 

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

Include it in the NgModule imports.

1
imports: [
2
    BrowserModule,
3
    ROUTING,
4
    FormsModule
5
]

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

1
<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:

1
import { Component } from '@angular/core';
2
3
@Component({
4
  selector: 'app-login',
5
  templateUrl: './login.component.html'
6
})
7
export class LoginComponent {
8
9
  constructor() {
10
      
11
  }
12
13
}

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

1
<h3>
2
    Login Component
3
</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 AppLogin Component -  Blogging AppLogin 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.

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

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

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

3
</div>

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

1
<form class="form-signin">
2
     <h2 class="form-signin-heading">Please sign in</h2>
3
     <label for="inputEmail" class="sr-only">Email address</label>
4
        <input name="email" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
5
        <label for="inputPassword" class="sr-only">Password</label>
6
        <input name="password"  type="password" id="inputPassword" class="form-control" placeholder="Password" required>
7
        <div class="checkbox">
8
          <label>
9
            <input type="checkbox" value="remember-me"> Remember me
10
          </label>
11
        </div>
12
    <button class="btn btn-lg btn-primary btn-block" type="button">Sign in</button>
13
</form>

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

1
.form-signin {
2
  max-width: 330px;
3
  padding: 15px;
4
  margin: 0 auto;
5
}
6
.form-signin .form-signin-heading,
7
.form-signin .checkbox {
8
  margin-bottom: 10px;
9
}
10
.form-signin .checkbox {
11
  font-weight: 400;
12
}
13
.form-signin .form-control {
14
  position: relative;
15
  box-sizing: border-box;
16
  height: auto;
17
  padding: 10px;
18
  font-size: 16px;
19
}
20
.form-signin .form-control:focus {
21
  z-index: 2;
22
}
23
.form-signin input[type="email"] {
24
  margin-bottom: -1px;
25
  border-bottom-right-radius: 0;
26
  border-bottom-left-radius: 0;
27
}
28
.form-signin input[type="password"] {
29
  margin-bottom: 10px;
30
  border-top-left-radius: 0;
31
  border-top-right-radius: 0;
32
}

Modify the @Component decorator to include the CSS style.

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

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

Login Screen Angular Blogging AppLogin Screen Angular Blogging AppLogin 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:

1
import { Injectable } from '@angular/core';
2
import { HttpClient } from '@angular/common/http';
3
4
@Injectable()
5
export class LoginService {
6
7
    constructor(private http: HttpClient){
8
9
	}
10
	
11
	validateLogin(){
12
		
13
	}
14
15
}

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

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

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

1
validateLogin(user: User){
2
	return this.http.post('/api/user/login',{
3
		username : user.username,
4
		password : user.password
5
	})
6
}

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:

1
import { Injectable } from '@angular/core';
2
import { HttpClient } from '@angular/common/http';
3
import { User } from '../models/user.model';
4
5
@Injectable()
6
export class LoginService {
7
8
    constructor(private http: HttpClient){
9
10
	}
11
	
12
	validateLogin(user: User){
13
		return this.http.post('/api/user/login',{
14
			username : user.username,
15
			password : user.password
16
		})
17
	}
18
19
}

Implementing User Login Validation

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

1
 <input name="email" [(ngModel)] = "user.username" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
2
 <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.

1
<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:

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

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

1
public user : User;
2
3
constructor(private loginService: LoginService) {
4
  this.user = new User();
5
}

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

1
export class User {
2
    constructor(){
3
		this.username = '';
4
		this.password = '';
5
	}
6
	public username;
7
	public password;
8
}

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

1
validateLogin() {
2
  if(this.user.username && this.user.password) {
3
  	this.loginService.validateLogin(this.user).subscribe(result => {
4
    console.log('result is ', result);
5
  }, error => {
6
    console.log('error is ', error);
7
  });
8
  } else {
9
  	alert('enter user name and password');
10
  }
11
}

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:

1
import { Component } from '@angular/core';
2
import { LoginService } from './login.service';
3
import { User } from '../models/user.model';
4
5
@Component({
6
  selector: 'app-login',
7
  templateUrl: './login.component.html',
8
  styleUrls: ['./login.component.css'],
9
  providers: [ LoginService ]
10
})
11
export class LoginComponent {
12
13
  public user : User;
14
15
  constructor(private loginService: LoginService) {
16
      this.user = new User();
17
  }
18
19
  validateLogin() {
20
  	if(this.user.username && this.user.password) {
21
  		this.loginService.validateLogin(this.user).subscribe(result => {
22
        console.log('result is ', result);
23
      }, error => {
24
        console.log('error is ', error);
25
      });
26
  	} else {
27
  		alert('enter user name and password');
28
  	}
29
  }
30
31
}

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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.