In this article, we will be building an angular5 application from scratch with step by step configuration and explanation.This single page application will be created using angular CLI command with different angular modules integrated with it such as RouterModule, HttpClientModule, AppRoutingModule, FormsModule. The application will have a sample login page styled with bootstrap and a user dashboard page. Once, the user is authenticated successsfully, he will be redirected to the dashboard page where he can see a list of users.
You can follow this article for Angular 8 integration with Spring Boot.
What's new in Angular5
Angular5 application is more faster,lighter and easy to use. It has material design capabilities to build beautiful and intuitive UI.New HttpClientModule is introduced which is a complete rewrite of existing HttpModule. It has typescript 2.4 supported now.
Generating Angular5 Application
To get started with Angular CLI, it is required to have node installed so that we can use the NPM tool. Executing following NPM commands generate an angular5 application named - angular5-example
npm install -g @angular/cli angular5-example ng new angular5-example cd angular5-example ng serve
Now we have our angular5 application ready to use and we can verify it on the browser at http://localhost:4200. By default angular application is available at port 4200 with command ng serve.
Now we can import this generated project in our IDE and start modifying it to build our login application. There are certain files generated with CLI command which we need to understand here. We have .angular-cli.json
file generated that has all the application configuration parameters. The configuration related to welcome html file as index.html
, main.ts
where all the modules are bundled. You can also find the final application output directory configuration and configuration specific to environment such as dev and prod can be found here.
We have package.json file that has information about all the project dependencies. We have tsconfig.json for typescript configuration.Inside the scr/app folder we have our components defined and when the request for localhost:4200 is made, AppComponent is loaded in the browser.
Now we will be removing these default contents and add codes to make our login application. As discussed earlier we will have 2 pages - one for login and the other for dashboard. Hence, let's create two components as login and user.
ng generate component login ng generate component user
Angular5 Project Structure
Now if you check your project, you will have two folders created with the name login and user which contains LoginComponent and UserComponent. The CLI has also made entries in app.module.ts for these two newly created components.
Routing in Angular5
Now let us configure the angular routing to route these pages based on the url. For this we will be creating app.routing.module.ts and configure our routes.
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {UserComponent} from '../user/user.component'; import {LoginComponent} from '../login/login.component'; const routes: Routes = [ { path: 'user', component: UserComponent }, { path: 'login', component: LoginComponent }, {path : '', component : LoginComponent} ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ], declarations: [] }) export class AppRoutingModule { }
Also, we need to import the same in our app.module.ts as declarations. Now to serve these routes include <router-outlet></router-outlet> in app.component.html. In the above configurations, we have mentioned to use LoginComponent as a default component and also configured url for which these componenents would be loaded. Now you can check if these configurations are working properly or not in the browser with url - http://localhost:4200/login and http://localhost:4200/user.
Login Component
Now let us add login form code in out login.component.html.
<div class="row"> <div class="col-md-6"> <h1>Login </h1> <form> <div class="form-group"> <label for="email">Email address:</label> <input type="email" class="form-control" id="email" name="email" [(ngModel)]="email"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd" name="passowrd" [(ngModel)]="password"> </div> <button class="btn btn-default" (click)="login()">Login</button> </form> </div> </div>
Here we have bind email and password with the model attribute.To use ngModel you require to import FormsModule in your app.module.ts. On the click of the login button, our login()
method defined in the login.component.ts will be invoked. This method validates the email and password and redirects user to user dashboard page. To make this example simple, we have hardcoded the email and password here but in real time application you will have APIs to validate user credentials. Also, you may require to save token and user info in the local cache after successfull validation. To build an end to end application with API integration, you can visit this - full stack angular5 application.
import { Component, OnInit } from '@angular/core'; import {Router} from "@angular/router"; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { email: string; password: string; constructor(private router : Router) { } ngOnInit() { } login() { debugger if(this.email == 'dhiraj@gmail.com' && this.password == 'password') { this.router.navigate(['user']); }else { alert("Invalid credentials.") } } }
Create Dashboard Component
Once the user is validated, he will be redirected to user dashboard page. To load data, we have app.service.ts that has code to generate fake users with some delay.
public getUsers() { let fakeUsers = [{id: 1, firstName: 'Dhiraj', lastName: 'Ray', email: 'dhiraj@gmail.com'}, {id: 1, firstName: 'Tom', lastName: 'Jac', email: 'Tom@gmail.com'}, {id: 1, firstName: 'Hary', lastName: 'Pan', email: 'hary@gmail.com'}, {id: 1, firstName: 'praks', lastName: 'pb', email: 'praks@gmail.com'}, ]; return Observable.of(fakeUsers).delay(5000); }
Now the same service is being used in our user.component.ts to load these users in user.component.html
import { Component, OnInit } from '@angular/core'; import {ApiService} from "../app.service"; import {User} from "./user.model"; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent implements OnInit { users: [User] constructor(private apiService: ApiService) { } ngOnInit() { this.apiService.getUsers().subscribe( data => this.users = data); } }
Following is our html for this dashboard page.
<div class="col-md-6"> <h2> User Details</h2> <table class="table table-striped"> <thead> <tr> <th class="hidden">Id</th> <th>FirstName</th> <th>LastName</th> <th>Email</th> </tr> </thead> <tbody> <tr *ngFor="let user of users"> <td class="hidden">{{user.id}}</td> <td>{{user.firstName}}</td> <td>{{user.lastName}}</td> <td>{{user.email}}</td> </tr> </tbody> </table> </div>
Following is our user dashboard page using anglar5 page.
Conclusion
Here we created our sample application using angular5. Now we can extend this article to have security in it. You can follow angular jwt authentication example to secure the angular5 application with JWT token.You can download the source from here.