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,
- 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 {}
- Bind the form from template to the component using ngModel syntax
<inputtype="text"class="form-control"id="name"required[(ngModel)]="model.name"name="name"/>
- Attach NgForm directive to the
<form>
tag in order to create FormControl instances and register them<form #registerForm="ngForm"> - Apply the validation message for form controls
<label for="name">Name</label><inputtype="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>
- 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
165
Read more
What is Angular Framework?
November 04, 2022
AngularWhat is a Angular module?
November 03, 2022
AngularWhat are the steps to use animation module?
October 31, 2022
Angular