Angular Template-Driven Forms: Simplifying User Input Handling
Tags: angular, javascript, typescript, tutorial
Published: 2023-09-01 05:59:26


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bn8oeatmmefvgsf085f0.png)

## Introduction

Angular continues to evolve, and so do its features and capabilities. In this article, we will explore how to create a template-driven form using the latest version of Angular. Template-driven forms remain a valuable tool for handling user input in web applications, and this updated example will help you get started with the latest practices.

## Prerequisites

Before we dive into the code, make sure you have Node.js and the Angular CLI installed on your system. You can install the Angular CLI globally using npm:

```bash
npm install -g @angular/cli
```

## Creating a New Angular Project

Let's start by creating a new Angular project using the Angular CLI:

```bash
ng new angular-template-forms
```

You'll be prompted to configure some project settings. For this tutorial, you can choose the default options.

## Creating a User Registration Form

Now, let's generate a component that will contain our user registration form:

```bash
ng generate component user-registration
```

### Building the User Registration Form

Open the `user-registration.component.html` file and add the following code to create a user registration form:

```html
<div class="container">
  <h2>User Registration</h2>
  <div class="container">
  <h2>User Registration</h2>
    <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
      <div class="form-group">
        <label for="firstName">First Name</label>
        <input type="text" id="firstName" name="firstName" [(ngModel)]="firstName" required minlength="2">
      </div>
  
      <div class="form-group">
        <label for="lastName">Last Name</label>
        <input type="text" id="lastName" name="lastName" [(ngModel)]="lastName" required>
      </div>
  
      <div class="form-group">
        <label for="email">Email</label>
        <input type="email" id="email" name="email" [(ngModel)]="email" required email>
      </div>
  
      <button type="submit" class="btn btn-primary" [disabled]="!userForm.valid">Submit</button>
    </form>
  </div>
</div>
```

In this form, we use the `ngModel` directive to bind form inputs to properties in our component, such as `firstName`, `lastName`, and `email`. The `required` attribute ensures that these fields cannot be submitted empty, while the `email` attribute enforces email format validation for the email field.

### Handling Form Submission

Now, let's handle form submission in the `user-registration.component.ts` file:

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

@Component({
  selector: 'app-user-registration',
  templateUrl: './user-registration.component.html',
  styleUrls: ['./user-registration.component.css']
})
export class UserRegistrationComponent {
  firstName: string = '';
  lastName: string = '';
  email: string = '';

  onSubmit() {
    console.log('Form submitted!');
    console.log('First Name:', this.firstName);
    console.log('Last Name:', this.lastName);
    console.log('Email:', this.email);
  }
}
```

In this component, we define the properties `firstName`, `lastName`, and `email` to store the form input values. The `onSubmit` method is called when the form is submitted, and it logs the form data to the console for demonstration purposes.

### Displaying the Form

To display the form in your application, open the `app.component.html` file and include the `<app-user-registration></app-user-registration>` element:

```html
<div style="text-align:center">
  <h1>Welcome to Angular Template-Driven Forms</h1>
</div>
<app-user-registration></app-user-registration>
```

### Running the Application

Now, you can start your Angular development server:

```bash
ng serve
```

Visit `http://localhost:4200` in your web browser, and you should see the user registration form.

## Form Validation and Error Handling

Let's enhance our form by adding some validation and error messages.

### Adding Validation

Open the `user-registration.component.html` file and update the form fields as follows:

```html
<div class="form-group">
  <label for="firstName">First Name</label>
  <input type="text" id="firstName" name="firstName" ngModel required minlength="2">
  <div *ngIf="userForm.controls.firstName.touched && userForm.controls.firstName.invalid" class="error-message">
    <div *ngIf="userForm.controls.firstName.hasError('required')">First Name is required.</div>
    <div *ngIf="userForm.controls.firstName.hasError('minlength')">First Name must be at least 2 characters long.</div>
  </div>
</div>
```

We added the `minlength` attribute to the first name input field to enforce a minimum length of 2 characters. Additionally, we display error messages only if the field has been touched and is invalid.

### Styling Error Messages

To style the error messages, add the following CSS to the `user-registration.component.css` file:

```css
.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}
```

This CSS ensures that error messages are displayed in red below the respective form fields.

### Testing Validation

Now, if you try to submit the form with an invalid first name, you will see the error message. Angular automatically updates the form's validity state based on the validation rules we defined.

[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5brcd5ndbmwq2ne01vvj.png)](https://buymeacoffee.com/chintanonweb)

## Conclusion

In this updated tutorial, we explored the basics of creating a template-driven form using the latest version of Angular. Template-driven forms remain a powerful tool for handling user input in Angular applications. As you continue to work with Angular, you can extend and customize your forms to meet your specific requirements.

Angular's evolving ecosystem and documentation provide ample resources to help you stay up-to-date and proficient in building web applications. Whether you're developing a simple contact form or a complex data entry system, Angular's template-driven forms can streamline the process and improve user experience. Happy coding!