InterviewHubPRO
Section Overview
Q258

Question 258 of 283

Part 10: Reactive Forms, Standalone Components, Signals & NgRx (256 - 283)

91%
Angular & Signals (283 Qs)•Part 10: Reactive Forms, Standalone Components, Signals & NgRx (256 - 283)

What are template driven forms?

Template driven forms are model-driven forms where you write the logic, validations, controls etc, in the template part of the code using directives. They are suitable for simple scenarios and uses two-way binding with [(ngModel)] syntax. For example, you can create register form easily by following the below simple steps,

  1. Import the FormsModule into the Application module's imports array
js
     import { BrowserModule } from '@angular/platform-browser';
     import { NgModule } from '@angular/core';
     import {FormsModule} from '@angular/forms'
     import { RegisterComponent } from './app.component';
     @NgModule({
       declarations: [
         RegisterComponent,
       ],
       imports: [
         BrowserModule,
         FormsModule
       ],
       providers: [],
       bootstrap: [RegisterComponent]
     })
     export class AppModule { }
  1. Bind the form from template to the component using ngModel syntax
html
  <input type="text" class="form-control" id="name"
    required
    [(ngModel)]="model.name" name="name">
  1. Attach NgForm directive to the <form> tag in order to create FormControl instances and register them
js
  <form #registerForm="ngForm">
  1. Apply the validation message for form controls
html
  <label for="name">Name</label>
  <input type="text" class="form-control" id="name"
         required
         [(ngModel)]="model.name" name="name"
         #name="ngModel">
  <div [hidden]="name.valid || name.pristine"
       class="alert alert-danger">
    Please enter your name
  </div>
  1. Let's submit the form with ngSubmit directive and add type="submit" button at the bottom of the form to trigger form submit.
html
  <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
  // Form goes here
  <button type="submit" class="btn btn-success" [disabled]="!registerForm.form.valid">Submit</button>

Finally, the completed template-driven registration form will be appeared as follow.

html
<div class="container">
<h1>Registration Form</h1>
<form (ngSubmit)="onSubmit()" #registerForm="ngForm">
  <div class="form-group">
    <label for="name">Name</label>
      <input type="text" class="form-control" id="name"
             required
             [(ngModel)]="model.name" name="name"
             #name="ngModel">
      <div [hidden]="name.valid || name.pristine"
           class="alert alert-danger">
        Please enter your name
      </div>
  </div>
  <button type="submit" class="btn btn-success" [disabled]="!registerForm.form.valid">Submit</button>
  </form>
</div>