Skip to main content

Template-driven Forms

Template-driven forms are a powerful feature provided by Angular that allows us to quickly create forms, with little effort. You simply declare the form and the controls on the template, and Angular takes care of creating the form control objects in the background. The template-driven forms are best suited for simple forms with a small number of fields.

Prerequisites

Before we start, make sure you have a basic understanding of Angular, HTML, CSS, and TypeScript. You should also have Angular CLI installed on your machine.

Setting Up the Application

Let's start by creating a new Angular application using the Angular CLI. Run the following command in your terminal:

ng new template-driven-forms

Navigate to the newly created project:

cd template-driven-forms

Creating a Simple Template-Driven Form

Open the app.component.html file and replace the existing code with the following:

<form>
<label>
Name:
<input type="text" [(ngModel)]="name">
</label>
<button type="submit">Submit</button>
</form>

In this snippet, we have created a simple form with a single input field for the name. The [(ngModel)] is a two-way data binding syntax. It binds the input to a property name of the component.

Let's declare the name property in our component. Open the app.component.ts file and add the name property as follows:

export class AppComponent {
name = '';
}

Importing the FormsModule

To use the template-driven forms, we need to import the FormsModule in our application. Open the app.module.ts file and update it as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
imports: [
FormsModule
],
})

Form and Field Validation

Angular provides a set of directives to validate the form fields. The most commonly used directives are required, minlength, and maxlength.

Let's add a validation to our name field. Update the input field in app.component.html as follows:

<input type="text" [(ngModel)]="name" required>

Now, the form will not be submitted unless the name field is filled.

Displaying the Form Value

Angular allows us to access the form value using the ngForm directive. Let's display the form value in our template. Update the app.component.html as follows:

<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<!-- form controls -->
</form>

<pre>{{ f.value | json }}</pre>

In this snippet, #f="ngForm" creates a local template variable f. We can use f.value to access the form value.

Conclusion

In this tutorial, we learned how to create a simple template-driven form using Angular. We also learned how to add validation to our form fields and how to display the form value. Template-driven forms are a simple and powerful feature of Angular that allows us to quickly create forms with little effort.