Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validating login form in angular 2

Tags:

angular

I have successfully implemented Http post request with my rest micro service .

Implemented the login application with the post request.

But i am unable to set validation to my login form.If the entered credentials are not correct the form should display me a message "invalid username/password.

Below shown is my code

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

import { GetService } from './home/get.service';
import { PostService } from './login/post.service';

import { routing } from "./app.routing";
import { RouterModule, Routes} from '@angular/router';


import { FormsModule ,ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

@NgModule({

  declarations: [AppComponent,HeaderComponent,LoginComponent,HomeComponent],

  imports: [RouterModule,BrowserModule, HttpModule , routing, FormsModule ,ReactiveFormsModule ],

  providers: [GetService,PostService],

  bootstrap: [AppComponent]

})

export class AppModule { }

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}

app.component.html

<div style="text-align:justify-all;">
  <h1>
    {{title}}
  </h1>

 <div class="container">
<router-outlet></router-outlet>
</div>

app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/homepage', pathMatch: 'full' },
{ path: 'homepage', component: LoginComponent },
{ path: 'homepage/home', component: HomeComponent }
];

export const routing = RouterModule.forRoot(APP_ROUTES);

header.component.ts

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

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

header.component.html

<div class="row">
<div class="col-xs-12"><ul class="nav nav-pills">
<li routerLinkActive="active"><a [routerLink]="['/homepage/home']">
<strong>Home</strong></a></li>
<li><a [routerLink]="['/homepage']"><strong>Logout</strong></a></li>
</ul></div>
</div>

Here is my login component where i have implemented the post request

login.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

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


export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string) 
 {
   this.MyService.checkByCredential(username, password)
      .subscribe(users => {
           if(users)
              this.router.navigate(['homepage/home']);
           else
              this.router.navigate(['homepage']); 
           }   );
                }}

login.component.html

<div class="container formWidth" style="text-align:center;">
  <h1> eSpace Login</h1><hr>
<br/>
     <h2>Login</h2>
    <form role="form">
      <div ng-control-group="credentials">
        <label for="username">Username</label>
        <input
          type="text"
          #username
          id="username"
          ng-control="username"
          required>
<br/>
        <label for="password">Password</label>
        <input
          type="password"
          #password
          id="password"
          ng-control="password"
          required>
      </div>
      <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
    </form>
</div>

post.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class PostService {
constructor(private http:Http) { }

 checkByCredential(username: string, password: string) {
 const user = { username: username, password: password };
 return this.http
    .post('http://localhost:8080/checkByCredential', user) 
    .map(result => result.json());
  } }

Here is my home component in which i implemented get request

home.component.ts

import { Component} from '@angular/core';
import { GetService } from './get.service';

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

export class HomeComponent{ 
title :string; 
data:any; 

constructor(private MyService: GetService){ 
this.title="Angular Service";  
} 

onClickToLoadUsers(e: any): void { 
this.loadUsers() 
e.preventDefault() 
} 

loadUsers() { 
this.MyService.GetUsers().subscribe(users => this.data = users); 
} 
}

home.component.html

    <app-header></app-header>
    <hr>
<p> <strong> Welcome to eSpace Home </strong></p>

<!-- <img src="/../../assets/i9.jpeg" class="img-rounded" alt="home" 
height="400" width="1150">-->

    <div style="margin-left:50px; height: 200px; overflow: auto;"> 
        <h4>Angular GET service</h4><hr>
    <button (click)="onClickToLoadUsers($event)">Load user</button><br/>
<br/>
             <table>
                 <tr><td>Username</td>&emsp;&emsp;<td>Password</td></tr>
                 <tr *ngFor= " let item of data">
             <td>{{ item.username }}</td>&emsp;&emsp;<td>{{ item.password }}
</td>
             </tr>
             </table>
            </div>

get.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class GetService {
constructor(private http:Http) { }


GetUsers(){
  return this.http.get('http://localhost:8080/checkUsers')
    .map(result => result.json());
           }
 }

when i submit my form with the username and password which is not in my database,it should display me a message "invalid username and password".

can anybody please help in implementing a reactive form with my application.

like image 935
Heena Avatar asked Mar 25 '26 01:03

Heena


1 Answers

Kindly check the below code and compare with your code, where I am mentioned by ** symbol in the below code and do those changes in your code.

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

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


export class LoginComponent {
  data:any;
 **IsLoggined:boolean = true;**

  constructor(private router:Router ,private MyService: PostService){**this.IsLoggined = true;** }

 checkByCredential(username: string, password: string) 
 {
   this.MyService.checkByCredential(username, password)
      .subscribe(users => {
           if(users)
              this.router.navigate(['homepage/home']);
           else
              **this.IsLoggined=false; 
               return false;**
           }   );
                }}

login.component.html

    <div class="container formWidth" style="text-align:center;">
      <h1> eSpace Login</h1><hr>
    <br/>
         <h2>Login</h2>
        <form role="form">
  **<div [hidden]='IsLoggined'  style="background-color:red;color:white"> invalid username and password </div>**
          <div ng-control-group="credentials">
            <label for="username">Username</label>
            <input
              type="text"
              #username
              id="username"
              ng-control="username"
              required>
    <br/>
            <label for="password">Password</label>
            <input
              type="password"
              #password
              id="password"
              ng-control="password"
              required>
          </div>
          <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
        </form>
    </div>
like image 197
Ramesh Rajendran Avatar answered Mar 28 '26 02:03

Ramesh Rajendran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!