Angular Template Driven Forms

In the previous article, you’ve seen the different types of Angular Forms and the difference between them. TDFs are easy-to-use forms. You’ve to write a bulk of code in an HTML file and less code in a TypeScript file. These forms are basically used when we’re making any simple apps.

What are Template Driven Forms in Angular?

Template Driven Forms are basically made of HTML forms that use ngForm directive with Two-way data binding in Angular.

How To Create a Template Driven Form in Angular?

Let’s make a simple registration form to understand template-driven forms in Angular.

Before going into the HTML file and creating a form, the first step is to import FormsModule in app.module.ts and add it to the imports array.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from "@angular/forms";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],

  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Now let’s go into the HTML file and write some code to create a  basic registration form.

<div>
  <h1>Registration Form</h1>
  <form #form="ngForm">
    <div>
      <input type="text" placeholder="Enter your name" name="name" ngModel>
    </div>
    <div>
      <input type="text" placeholder="Enter your mobile number" name="phone" ngModel>
    </div>
    <div>
      <input type="text" placeholder="Enter your email" name="email" ngModel>
    </div>
    <div>
      <input type="text" placeholder="Enter your address" name="address" ngModel>
     </div>
    <button type="submit">SUBMIT</button>
  </form>
  {{form.value | json}}
</div>
  • Angular has its directive called ngForm directive, which gives all the valuable information about that particular form.
  • By using template reference variable #form, we’re holding a reference to the ngFrom
  • ngModel directive is used to track the values of the form control.

NOTE: If ngModel is used within a form, the name attribute must be set; otherwise, it’ll throw an error message to the console.

Output:

angular template driven forms example

  • .value is used to get values of all the form controls.
  • We’re displaying the data using interpolation and pipes into the view.

NOTE: We’ve covered interpolation and pipes in some of our previous articles. We strongly recommend checking them out to make the most of this article.

Conclusion

We hope this article has cleared all your doubts on Template Driven Forms and how they can be used in making simple forms. In the next articles, you’ll learn about Reactive Forms in Angular.

Read Next: Angular Reactive Forms

Leave a Reply

Your email address will not be published. Required fields are marked *