I am here to continue the discussion around AngularJS 2.0. So far, we have discussed about data binding, input properties, output properties, pipes, viewchild, Directives, Services including routes in Angular 2.0. Now, in this article, I will discuss how to create template based form, using Angular form module in Angular 2.0. In case, you did not have a look at the previous articles of this series, go through the links mentioned below.
Angular 2.0 Forms – What is it?
In today's Web Application, a large category of front end Applications are very much form dependent, especially in the case of large enterprise type development. Most of these Applications contains simply a huge or large form, which contains multiple tabs, dialogs and with non – trivial business validation logic. Forms are very important of part of the Applications. In a component based Application, we always want to split the forms into a small and reusable piece of code, which is stored within the Smart and Dumb components. These components are normally spread over the entire Application, which provides several architectural benefits including flexibility and design changes.
In Angular 2.0 Framework, we have two different mechanisms, which are related to form-binding.
- Template Driven Form.
- Reactive or Model Driven Forms.
In this article, we will discuss about Template Driven Forms.
Angular 2 tackles forms via the famous ngModel. The instantaneous two-way data binding of ng-model in Angular 1 is really a life-saver as it allows to transparently keep in synchronization; a form with a view model. Forms are built with this Directive can only be tested in an end to end test because this requires the presence of a DOM, but still this mechanism is very useful and simple to understand. Unlike the case of AngularJs 1.0, ngModel and other form-related Directives are not available by default, we need to explicitly import them in our Application module. To include the form module in our Application, we need to inject the FormModule in our Application and bootstrapped it.
Template Driven Forms features
- Easy to use.
- Suitable for simple scenarios and fails for complex scenarios.
- Similar to Angular 1.0.
- Two way data binding (using [(NgModel)] syntax).
- Minimal component code.
- Automatic track of the form and its data.
- Unit testing is another challenge.
Advantages and Disadvantages of Template Driven Forms
In this simple example, we cannot really see it, but keeping the template as the source of all form validation truth is something that can become pretty hairy rather than quickly doing it.
As we add more and more validator tags to a field or when we start adding complex cross-field validations the readability of the form decreases to the point, where it will be hard to hand it off to a Web designer.
The up-side of this way of handling forms is its simplicity and its probably more than enough to build a very large range of forms.
On the downside, the form validation logic cannot be unit tested. The only way to test this logic is to run an end to end test with a Browser. For example, using a headless Browser like PhantomJs.
To demonstrate the above concept, we will develop the code given below. For the code, add the files given below with the code.
app.component.homepage.html
- <h2>Template Driven Form</h2>
- <div>
- <form #signupForm="ngForm" (ngSubmit)="registerUser(signupForm)">
- <table style="width:60%;" cellpadding="5" cellspacing="5">
- <tr>
- <td style="width :40%;">
- <label for="username">User Name</label>
- </td>
- <td style="width :60%;">
- <input type="text" name="username" id="username" [(ngModel)]="username" required>
- </td>
- </tr>
- <tr>
- <td style="width :40%;">
- <label for="email">Email</label>
- </td>
- <td style="width :60%;">
- <input type="text" name="email" id="email" [(ngModel)]="email" required>
- </td>
- </tr>
- <tr>
- <td style="width :40%;">
- <label for="password">Password</label>
- </td>
- <td style="width :60%;">
- <input type="password" name="password" id="password" [(ngModel)]="password" required>
- </td>
- </tr>
- <tr>
- <td style="width :40%;"></td>
- <td style="width :60%;">
- <button type="submit">Sign Up</button>
- </td>
- </tr>
- </table>
- </form>
- <div *ngIf="showMessage">
- <h3>Thanks You {{formData.username}} for registration</h3>
- </div>
- </div>
app.component.homepage.ts
- import { Component, OnInit, ViewChild } from '@angular/core';
- import { NgForm } from '@angular/forms';
-
- @Component({
- moduleId: module.id,
- selector: 'home-page',
- templateUrl: 'app.component.homepage.html'
- })
-
- export class HomePageComponent implements OnInit {
-
- private formData: any = {};
- private showMessage: boolean = false;
-
- constructor() {
- }
-
- ngOnInit(): void {
- }
-
- registerUser(formdata: NgForm) {
- this.formData = formdata.value;
- this.showMessage = true;
- }
- }
app.module.ts
- import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from "@angular/forms";
-
- import { HomePageComponent } from './src/app.component.homepage';
-
- @NgModule({
- imports: [BrowserModule, FormsModule],
- declarations: [HomePageComponent],
- bootstrap: [HomePageComponent]
- })
- export class AppModule { }
index.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>Angular2 - Template Driven Form </title>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link href="../resources/style/bootstrap.css" rel="stylesheet" />
- <link href="../resources/style/style1.css" rel="stylesheet" />
-
- <script src="../resources/js/jquery-2.1.1.js"></script>
- <script src="../resources/js/bootstrap.js"></script>
-
- <script src="../node_modules/core-js/client/shim.min.js"></script>
- <script src="../node_modules/zone.js/dist/zone.js"></script>
- <script src="../node_modules/reflect-metadata/Reflect.js"></script>
- <script src="../node_modules/systemjs/dist/system.src.js"></script>
- <script src="../systemjs.config.js"></script>
- <script>
- System.import('app').catch(function (err) { console.error(err); });
- </script>
-
- <script>document.write('<base href="' + document.location + '" />');</script>
- </head>
- <body>
- <home-page>Loading</home-page>
- </body>
- </html>
main.ts
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
-
- import { AppModule } from './app.module';
-
- const platform = platformBrowserDynamic();
- platform.bootstrapModule(AppModule);
Now, run the code and the output is shown below.