Template-driven forms are simpler to use and more declarative. They rely heavily on Angular’s directives and are defined directly in the HTML template. Angular automatically creates the form model based on the directives and inputs used in the template.
Angular Template Driven Form is a old way to create the form in Angular. Most of work of Angular form is done in component html file like componentName.component.html. We define Validation logic, etc in this component.html file.
There are some steps to create the Template Driven form.
Step1) Firstly include FormsModule in app.module.ts file
import { FormsModule } from '@angular/forms';
Step2) Now, include FormsModule into imports array which is into @NgModule() object.
@NgModule({
imports: [
FormsModule
]
});
Step3) Now, include NgForm from the ‘@angular/forms’ in users.component.ts file
import { NgForm } from '@angular/forms';
Step4) Now, create the html code into users.component.html file
There are some steps used to create template Driven Form.
1) formname start with # tag and equal to ngForm
2) Use ngModel is a directive and it is used to bind the fields like input field, select field, etc.
<div class="container">
<div class="col-md-3"></div>
<div class="col-md-6 text-center">
<h1>Add User</h1>
<form id="" #userForm="ngForm" (ngSubmit) = "submitUserform(userForm)" class="form">
<div class="col-md-12 row">
<div class="col-md-4">
<label>User Name</label>
</div>
<div class="col-md-8">
<input type="text" name="userName" ngModel/>
</div>
</div>
<div class="col-md-12 row" style="height: 15px"></div>
<div class="col-md-12 row">
<div class="col-md-4">
<label>User Age</label>
</div>
<div class="col-md-8">
<input type="text" name="userAge" ngModel/>
</div>
</div>
<div class="col-md-12 row" style="height: 15px"></div>
<div class="col-md-12 row" align="center">
<input type="submit" name="userSubmit" value="Add User" />
</div>
</form>
</div>
<div class="col-md-3"></div>
</div>
Step5) Now, define the code into users.component.ts file.
export class UsersComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
submitUserform(userForm:NgForm){
console.log("Username-",userForm.value.userName);
console.log("Userage-",userForm.value.userAge);
}
}
Step6) Now you can see the user form into browser.
Step7)When the user fill the details and click on the AddUser button then you can get the value into the console.