Angular Forms and Validation: Building User-Friendly Input Forms

Article by: Manish Methani

Last Updated: September 14, 2021 at 2:04pm IST
7 min 44 sec

Table of Contents:

Introduction

Forms are an essential part of web applications, allowing users to interact with your website. In Angular, you can create user-friendly input forms with ease. In this post, we'll guide you through the process of building input forms and implementing validation using Angular, using an example project.

Understanding Angular Forms

Angular offers two approaches for creating forms: Template-Driven Forms and Reactive Forms. Let's understand each approach with an example project.

Example Project: User Registration Form

For our example project, we'll build a simple user registration form with fields for username, email, and password.

Template-Driven Forms

Template-Driven Forms are ideal for simple forms. In your project:

  1. Import FormsModule: In your app.module.ts file, import FormsModule from @angular/forms.
import { FormsModule } from "@angular/forms";

@NgModule({
  imports: [FormsModule],
  // ...
})
  1. Create the Template: In your component's HTML file (user-registration.component.html), create the form using Angular directives:
  <form #userForm="ngForm">
    <div class="form-group">
      <label for="username">Username</label>
      <input type="text" id="username" name="username" [(ngModel)]="user.username" required>
    </div>
    <div class="form-group">
      <label for="email">Email</label>
      <input type="email" id="email" name="email" [(ngModel)]="user.email" required email>
    </div>
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" id="password" name="password" [(ngModel)]="user.password" required minlength="8">
    </div>
    <button type="submit" [disabled]="userForm.invalid">Register</button>
  </form>
  1. Access Form Data: You can access form data using the template reference (#userForm) and ngModel.

Reactive Forms

Reactive Forms provide more control and are suitable for complex forms. In our project:

  1. Import ReactiveFormsModule: In your app.module.ts file, import ReactiveFormsModule from @angular/forms.
import { ReactiveFormsModule } from "@angular/forms";

@NgModule({
  imports: [ReactiveFormsModule],
  // ...
})
  1. Create the Form Control: In your component file (user-registration.component.ts), define the form controls, form group, and form builder:
import { FormBuilder, FormGroup, Validators } from "@angular/forms";

export class UserRegistrationComponent {
  userForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      username: ["", [Validators.required]],
      email: ["", [Validators.required, Validators.email]],
      password: ["", [Validators.required, Validators.minLength(8)]],
    });
  }
}
  1. Bind to the Template: In your component's HTML file (user-registration.component.html), bind the form controls:
  <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="username">Username</label>
      <input type="text" id="username" formControlName="username">
    </div>
    <div class="form-group">
      <label for="email">Email</label>
      <input type="email" id="email" formControlName="email">
    </div>
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" id="password" formControlName="password">
    </div>
    <button type="submit" [disabled]="userForm.invalid">Register</button>
  </form>

Form Validation in Angular

Form validation is crucial for ensuring data integrity. Angular provides built-in validators and the ability to create custom validators.

Example Project: Adding Validation

Let's add validation to our user registration form.

Built-in Validators

Angular offers various built-in validators like required, minLength, maxLength, and pattern. For example, we added required, email, and minlength validators to the email and password fields.

Custom Validators

You can create custom validators for specific validation needs. For instance, you can create a custom validator to check if a username is available:

function usernameAvailabilityValidator(control: AbstractControl): { [key: string]: boolean } | null {
  const username = control.value;
  // Check availability logic here
  if (/* username is not available */) {
    return { "usernameTaken": true };
  }
  return null;
}

// Add the validator to your form control
this.userForm = this.fb.group({
  username: ["", [Validators.required], [usernameAvailabilityValidator]],
});

Displaying Validation Errors

Displaying validation errors to users in a user-friendly way is crucial. We can use Angular's ngIf and ngClass directives for this purpose:

  <div *ngIf="userForm.get("username").invalid && userForm.get("username").touched">
    <div *ngIf="userForm.get("username").hasError("required")">Username is required.</div>
  </div>

Conclusion

Creating user-friendly input forms with Angular is a breeze, thanks to its powerful form handling and validation capabilities. Whether you choose Template-Driven Forms or Reactive Forms depends on your project's requirements, but both offer robust solutions for building forms.

In our example project, we built a user registration form with validation. You can expand upon this project to include more features and customize it to fit your application's needs.

Remember to follow best practices for form validation, and your users will appreciate the user-friendly experience you provide.

Happy coding!

Additional Resources

If you are eager to take your web development skills to the next level, consider enrolling in the Codzify Full Stack Web Development course . This comprehensive course covers everything you need to excel in web development. Become a certified Full Stack Web Developer.

FAQ

1. What are Angular Forms?

Angular Forms are a crucial part of web applications that enable user interaction by allowing users to input data and submit it to the server. They are used for tasks like user registration, login, and data submission.

2. What are the two approaches to creating forms in Angular?

In Angular, you can create forms using two approaches: Template-Driven Forms and Reactive Forms. Template-Driven Forms rely on directives in the template, while Reactive Forms use a programmatic approach to define forms using TypeScript.

3. When should I use Template-Driven Forms?

Template-Driven Forms are suitable for simpler forms with basic validation requirements. They are easier to set up and ideal for forms that don"t require complex logic or dynamic form controls.

4. When should I use Reactive Forms?

Reactive Forms are more suitable for complex forms with dynamic form controls, advanced validation, and scenarios where you need more programmatic control over your forms. They offer greater flexibility and scalability.

Simplified Coding for Beginners.








Download the Codzify
Mobile App


Mobile App Development, Web App Development, Programming Languages, Latest Tech News & lot more.

Codzify Mobile App

A self-paced learning Courses Created by an Engineer
For Engineers.

Premium

The Complete Angular Course

Instructor: Manish Methani

Explore Curriculum
Free

C Programming for Absolute Beginners

Instructor: Manish Methani

Start Watching
Premium

Flutter Mobile App Development Course

Instructor: Manish Methani

Explore Curriculum
Free

Learn HTML, CSS & Bootstrap

Instructor: Manish Methani

Start Watching

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test
include_once 'codzify-footer.php'; ?>