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:
Root Component
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.
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:
Login Component
Save the above changes and restart the server. As the per the routes defined when the application loads the LoginComponent
will get displayed.
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.
Place a wrapper around the app-root
in the index.html
page.
Add the following HTML to the login.component.html
page.
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.
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
.
Add a click event to the sign in button.
Here is how the modified login.component.html
looks:
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.
Powered by WPeMatico