Friday, 13 December 2024

Simple Angular Template Driven Form

Angular provides two types of forms in Angular namely Template Driven Form and Reactive Form. On this post, we will see a simple example of a Template Driven Form. Angular version used here is 19.

First, add FormsModule in app.module.ts:
import { FormsModule } from '@angular/forms';
. . .

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

Then the HTML elements:
<form #studentForm="ngForm" (ngSubmit)="submitStudentForm()">
  <div>
    <label for="firstName">Student Name:</label>
    <input type="text" id="firstName" [(ngModel)]="model.firstName" name="firstName" placeholder="First Name" />
    <input type="text" id="lastName" [(ngModel)]="model.lastName" name="lastName" placeholder="Last Name" />
  </div>
  <div>
    <label for="email">Email:</label>
    <input type="text" id="email" [(ngModel)]="model.email" name="email" />
  </div>
  <button type="submit">Update</button>
</form>
Note that we need to add a template reference variable, '#theFormName' and set its value to ngForm, in our example is <form #studentForm="ngForm">. In the example we also use [(ngModel)] on input fields for two ways data binding. name attribute for each input is also required by ngForm, otherwise it won't work.

Finally on the .ts file:
export class StudentComponent {

  model: Student = {
    firstName: 'John',
    lastName: 'Doe',
    email: 'john.doe@example.com'
  };

  submitStudentForm(): void {
	. . .
  }
}