Template-driven forms – Handling User Inputs: Forms-1

Since the early days of web applications, before the concept of Single Page Applications (SPAs), in HTML 2, the <form> tag has been used to create, organize, and send forms to the backend.

In common applications, such as banking systems and health applications, we use forms to organize the inputs that our users need to perform in our systems. With such a common element in web applications, it is natural that Angular, a framework whose philosophy is batteries included, offers this feature to its developers.

In this chapter, we will delve into the following forms features in Angular:

  • Template-driven forms
  • Reactive forms
  • Data validation
  • Custom validations
  • Typed reactive forms

By the end of this chapter, you will be able to create maintainable and fluid forms for your user, in addition to improving your productivity with this type of task.

Technical requirements

To follow the instructions in this chapter, you’ll need the following:

The code files for this chapter are available at https://github.com/PacktPublishing/Angular-Design-Patterns-and-Best-Practices/tree/main/ch6.

During the study of this chapter, remember to run the backend of the application found in the gym-diary-backend folder with the npm start command.

Template-driven forms

Angular has two different ways of working with forms: template-driven and reactive. First, let’s explore template-driven forms. As we can see by the name, we maximize the use of the capabilities of the HTML template to create and manage the data model linked to the form.

We will evolve our Gym Diary application to better exemplify this concept. In the following command line, we use the Angular CLI to create the new page component:
ng g c diary/new-entry-form-template

To access the new assignment form, we’ll refactor the journal page component so the Add New Entry button takes the user to the component we created.

Let’s add to the DiaryModule module the import of the framework module responsible for managing the application’s routes:
.
.
.
import {
RouterModule
 } from ‘@angular/router’;
@NgModule({
 declarations: [
   DiaryComponent,
   EntryItemComponent,
   ListEntriesComponent,
   NewItemButtonComponent,
   NewEntryFormTemplateComponent,
 ],
 imports: [CommonModule, DiaryRoutingModule,
RouterModule
],
})
export class DiaryModule {}

With the RouterModule module imported, we will be able to use Angular’s route services. For more details on routing, see Chapter 7, Routes and Routers. We will add the new component to a route in the DiaryRoutingModule module:
.
.
.
import { NewEntryFormTemplateComponent } from ‘./new-entry-form-template/new-entry-form-template.component’;
const routes: Routes = [
  {
    path: ”,
    component: DiaryComponent,
  },
  {
    path: ‘new-template’,
    component: NewEntryFormTemplateComponent,
  },
];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class DiaryRoutingModule {}

To be able to compare the two form creation approaches, we will create a route for each example component that we are going to create. Here, the URL /home/new-template will direct us to the template-driven form route.

We will now refactor DiaryComponent to modify the behavior of the Add New Entry button:


.
.
.
import { Router } from ‘@angular/router’;
@Component({
  templateUrl: ‘./diary.component.html’,
  styleUrls: [‘./diary.component.css’],
})
export class DiaryComponent implements OnInit {
  private exerciseSetsService = inject(ExerciseSetsService);
  private router = inject(Router)
.
.
.
  addExercise(newSet: ExerciseSet) {
    this.router.navigate([‘/home/new-template’])
  }
.
.
.
}

First, we need to inject Angular’s router service.We change the addExercise method to use the service and, using the navigate method, direct to the page.

We can proceed to the HTML template of our form in the new-entry-form-template.component.html file and place only the elements of the form:
<div class=”flex h-screen items-center justify-center bg-gray-200″>
  <form class=”mx-auto max-w-sm rounded bg-gray-200 p-4″>
      .
.
.
      <input
        type=”date”
        id=”date”
         name=”date”
     />
.
.
.
      <input
        type=”text”
        id=”exercise”
        name=”exercise”
      />
.
.
.
      <input
        type=”number”
        id=”sets”
        name=”sets”
      />
  </div>
  <input
    type=”number”
    id=”reps”
    name=”reps”
  />
   </div>
   <div class=”flex items-center justify-center”>
     <button
       type=”submit”
     >
     Add Entry
     </button>

Leave a Reply

Your email address will not be published. Required fields are marked *

Privacy Policy | Cookie Policy | Cookies Settings | Terms & Conditions | Accessibility | Legal Notice