Introduction

In Angular applications, creating interactive forms that communicate with backend servers is a common requirement. This tutorial walks through the development of a simple login form using Angular's HttpClient module to send data to a backend API and handle responses.

Prerequisites

Before we begin, ensure you have.

Step 1. Setting Up the Component

First, let's create an Angular component where our login form and related functionality will reside.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  results: any;
  hide = true;
  constructor(private http: HttpClient, private router: Router) {}
  title = 'my-appweb';
  public datachild: string = "this is parent data view ";
  public datachild1: string = "this is parent data1";
  public dataFromCompTwo: string = '';
  receiveDataFromChild(event: any) {
    this.dataFromCompTwo = event;
  }
  onSave() {
    debugger;
    var getval = [];
    var num1 = (document.getElementById("username") as HTMLInputElement).value;
    var num2 = (document.getElementById("password") as HTMLInputElement).value;
    getval.push(num1, num2);
    console.log(getval);
    this.http
      .post<any>('http://220.225.104.151:81/PlayerLogin', getval)
      .subscribe(data => {
        debugger;
        console.log(data[0][0].Status);
        if (data[0][0].Status == 0) {
          alert("Login successfully")
        } else {
          alert("invalid username")
        }
        debugger;
        console.log(data);
      });
  }
}

Explanation

Step 2. Creating the HTML Template

Now, let's define the HTML template (app.component.html) to display the login form.

<div>
    <h3>Login</h3>
    <label>Username</label>
    <input type="text" id="username" value=""> <br>
    <label>Password</label>
    <input type="password" id="password" value=""> <br>
    <button (click)="onSave()">Login</button>
</div>

Explanation

Step 3. Integrating with Backend

Ensure your backend API (http://110.115.104.111:111/PlayLogin in this case) is configured to accept POST requests with username and password parameters. Adjust the endpoint and parameters as per your backend requirements.

Conclusion

This basic example demonstrates how to implement a simple login form in Angular, utilizing Angular's HttpClient for making HTTP requests. For production applications, consider enhancing security by implementing HTTPS and validating inputs both client-side (Angular forms) and server-side.