0
0
AngularHow-ToBeginner · 4 min read

How to Create a Login Form in Angular: Step-by-Step Guide

To create a login form in Angular, use ReactiveFormsModule to build a form group with controls for username and password. Bind the form to your template using formGroup and handle submission with a method that processes the form values.
📐

Syntax

Use Angular's FormGroup and FormControl classes to create a reactive form. Import ReactiveFormsModule in your module. In your component, define a FormGroup with controls for each input field. In the template, bind the form group with [formGroup] and each input with formControlName. Handle form submission with (ngSubmit).

typescript
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  loginForm = new FormGroup({
    username: new FormControl('', Validators.required),
    password: new FormControl('', Validators.required)
  });

  onSubmit() {
    if (this.loginForm.valid) {
      console.log('Form Submitted!', this.loginForm.value);
    }
  }
}
💻

Example

This example shows a complete Angular login form using reactive forms. It includes validation to require username and password, and logs the form data on submit.

typescript
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { LoginComponent } from './login.component';

@NgModule({
  declarations: [AppComponent, LoginComponent],
  imports: [BrowserModule, ReactiveFormsModule],
  bootstrap: [AppComponent]
})
export class AppModule {}

// login.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-login',
  template: `
    <form [formGroup]="loginForm" (ngSubmit)="onSubmit()" aria-label="Login form">
      <label for="username">Username:</label>
      <input id="username" type="text" formControlName="username" aria-required="true" />
      <div *ngIf="loginForm.get('username')?.invalid && loginForm.get('username')?.touched" style="color:red;">
        Username is required.
      </div>

      <label for="password">Password:</label>
      <input id="password" type="password" formControlName="password" aria-required="true" />
      <div *ngIf="loginForm.get('password')?.invalid && loginForm.get('password')?.touched" style="color:red;">
        Password is required.
      </div>

      <button type="submit" [disabled]="loginForm.invalid">Login</button>
    </form>
  `
})
export class LoginComponent {
  loginForm = new FormGroup({
    username: new FormControl('', Validators.required),
    password: new FormControl('', Validators.required)
  });

  onSubmit() {
    if (this.loginForm.valid) {
      alert('Login successful for user: ' + this.loginForm.value.username);
    }
  }
}
Output
A login form with username and password fields appears. If fields are empty and touched, error messages show. The login button is disabled until both fields are filled. On submit, an alert shows the username.
⚠️

Common Pitfalls

  • Not importing ReactiveFormsModule in your Angular module causes errors.
  • Forgetting to bind formGroup in the template breaks form control connections.
  • Not adding validators can allow empty submissions.
  • Using ngModel with reactive forms causes conflicts; use only reactive form bindings.
typescript
/* Wrong: Missing ReactiveFormsModule import */
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LoginComponent } from './login.component';

@NgModule({
  imports: [BrowserModule], // ReactiveFormsModule missing
  declarations: [LoginComponent],
  bootstrap: [LoginComponent]
})
export class AppModule {}

/* Right: Add ReactiveFormsModule */
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { LoginComponent } from './login.component';

@NgModule({
  imports: [BrowserModule, ReactiveFormsModule],
  declarations: [LoginComponent],
  bootstrap: [LoginComponent]
})
export class AppModule {}
📊

Quick Reference

  • Import ReactiveFormsModule in your module.
  • Create a FormGroup with FormControl instances in your component.
  • Bind the form in the template with [formGroup] and inputs with formControlName.
  • Use validators like Validators.required to enforce input rules.
  • Handle form submission with (ngSubmit) and check form.valid.

Key Takeaways

Always import ReactiveFormsModule to use reactive forms in Angular.
Define your form structure in the component using FormGroup and FormControl.
Bind your form and controls properly in the template with formGroup and formControlName.
Add validators to ensure required fields are filled before submission.
Handle form submission with a method that checks form validity and processes data.