Angular 7 User Login rest API with Bootstrap form

DINESH Adhikari
2 min readAug 18, 2019

--

In this tutorial, we will learn user login with the post API request with the beautiful Bootstrap(v4) form UI

Live Demo | Project on Github

Create a new project with the help of Angular cli And install the angular Bootstrap as well.

and then start the project. ng serve

Then visit http://localhost:4200/. If all’s well, you should see Hello Your-Project-Name.

Now create a login form with the help of bootstrap from.
and add formControlName, formGroup, ngSubmit action etc.
See below code

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()"><div class="form-group"><label for="exampleInputEmail1">Email address</label><input type="email" class="form-control" placeholder="Enter email" formControlName="email"[ngClass]="{'is-invalid': submitted && loginForm.controls.email.errors}"></div><div class="form-group"><label for="exampleInputPassword1">Password</label><input type="password" class="form-control" placeholder="Password" formControlName="password"[ngClass]="{'is-invalid': submitted && loginForm.controls.email.errors}" ></div><div class="form-group form-check"><input type="checkbox" class="form-check-input" id="exampleCheck1"><label class="form-check-label" for="exampleCheck1">Check me out</label></div><button type="submit" class="btn btn-primary">Submit</button></form>

And now we will write a function with onSubmit() in .ts file Github

onSubmit() {this.submitted = true;if (this.loginForm.invalid) {return;}
let body = {
email: this.loginForm.value.email,password: this.loginForm.value.password};console.log(body);}

And now we will show the value of the form under control in On Submit.

Good Job ✌👍

Create new authentication.service.ts file

ng g s authentication

We will create a login functions in the authentication.service.ts file.

login(body) {return this.http.post<any>(this.baseUrl + "user-login", body).pipe(map(data => {if (data.success) {//do some actionlocalStorage.setItem("IsLogin", "true")}return data}))}

Mention the ApiURL in your environment.ts file.
apiUrl: ‘http://localhost:4200/'

The authentication service is used to login and logout of the application, to login it Submit the credentials to the api and checks the response we have got from back-end. If the response is successful, we will set up login:true in storage.
And if unsuccessful, we will show a error message there. 👇

if (data.success) {//do some action
//localStorage.setItem("ActiveUser", JSON.stringify(data))
} else {//do some action//show error message}

This is why we will save logged in user details are stored in local storage so the user will stay logged in if they refresh the browser and also between browser sessions until they logout.

Thanks

Code in Github

--

--