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
    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 {}
  2. Bind the form from template to the component using ngModel syntax
    <input
    type="text"
    class="form-control"
    id="name"
    required
    [(ngModel)]="model.name"
    name="name"
    />
  3. Attach NgForm directive to the <form> tag in order to create FormControl instances and register them
    <form #registerForm="ngForm">
  4. Apply the validation message for form controls
    <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>
  5. Let's submit the form with ngSubmit directive and add type="submit" button at the bottom of the form to trigger form submit.
    <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
    // Form goes here
    <button type="submit" class="btn btn-success" [disabled]="!registerForm.form.valid">
    Submit
    </button>
    </form>

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

<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>

May 12, 2022
161