Skip to content
NADEEM AKHTAR (FULL STACK DEVELOPER) edited this page Sep 30, 2016 · 10 revisions

There are two ways to build forms in Angular 2, namely template-driven and model-driven.

Model-Driven or Template-Driven?

It depends on. If you are not doing unit testing (of course you should!), or you have the simple form, go ahead with template-driven forms.

Template-Driven Approach

Introduction

Angular 2 derives the form for you, whenever it encounters a

tag in your template. You still have to set up the controls by assigning ngControl directives.

We will build a Login form to capture user login data based on ## Login Model class that exist in path "core/models/login" & account.service Service class that exist in src/appcore/services/account.service.

Before Start working on Template Driven forms Don't forget to import "FormsModule" and add into "imports" Array. Unlike the case of AngularJs, ngModel and other form-related directives are not available by default, we need to explicitly import them in our application module,

for reference check account.module.ts file in "account/account.module.ts"

import { FormsModule } from '@angular/forms';

The account.module

Because we are using the modular approach for our boilerplate application that gives us the flexibility to play only with the specific module, to implement login functionality we only need to play around account module.

How our account.module file will look like refer to src/app/account/account.module.ts file

The login.component.ts file

Login component provides us functionality for initializing our form module && capture form data from view in our case we are using login model class.

How our login.component.ts file will look like refer to src/app/account/login/login.component.ts file

The account.service.ts file

This is our service class that is used to communicate with server basically all HTPP action will perform in this class. How our login.component.ts file will look like refer to src/app/account/login/login.component.ts file

The HTML View

How our HTML view will look like please refer to src/app/account/login/account.componenet.html file

For more information visit

  1. http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/
  2. https://angular.io/docs/ts/latest/guide/forms.html
Clone this wiki locally