In this article, I am going to explain how to submit form data to the server in angular 2 using model-driven reactive forms, when I was building forms in angular 1.3 for my carpooling angular application ( ), I have used template driven forms in which we need to bind every form control to ng-model and access those values in the controller using $scope object
The template-driven forms are easy to develop but hard to do unit testing because of asynchronous nature, when you want to deal with complex forms and want to do unit testing then you need to use model-driven forms

Step 1: Creating angular project

I have used Angular CLI to generate an initial project structure and  Visual Studio Code IDE for development of component’s, if you are new to Visual Studio Code IDE then I suggest you refer this article setting up visual studio code ide for angular 2
Once, the initial project structure is generated, to create new Angular 2 component’s we need to run ng generate components command, the generated angular 2 component and project structure is something like as shown in fig

Step 2: Registration Component

Once again, I am using angular CLI to create component’s and we need to run below command to generate angular 2 registration component

ng generate component RegistrationComponent

Once the registration component is created then what you need to is just open the registration.component.html file and replace existing code with below angular 2 form code

<div class="login-form" >
			    <div class="close"> </div>
					<div class="head">
					<div class="head-info">
						<h1>SIGN UP</h1>
						<h2>Hello and Welcome! Tell us a bit about you</h2>
				<form method="post" novalidate="" [formGroup]="registrationForm" (ngSubmit)="submit($event)">
						<input type="text" formControlName="firstName"  name="displayName" class="text" value="Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}" ><a href="#" class=" icon user"></a>
						<input type="text" formControlName="email"  class="text" value="Email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}" ><a href="#" class=" icon mail"></a>
						<input type="password" formControlName="password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}"><a href="#" class=" icon lock"></a>
						<input placeholder="confrmPassword" type="text" formControlName="confrmPassword"  name="confrmPassword" class="text" value="Confirm Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Confirm Password';}" ><a href="#" class=" icon user"></a>
					<div class="p-container">
								<input type="submit" value="SIGN UP" >
							<div class="clear"> </div>

here, I am using novalidate to disable form submission instead of that I am using ngSubmit to submit a form, on clicking of submit button we are calling submit function by passing form values and validation status

<form method="post" novalidate="" [formGroup]="registrationForm" (ngSubmit)="submit(registrationForm.value, registrationForm.valid)">

Here, the form control helps us to perform validations on assigned input control’s, if you see the above html code every input control has one directive called  “formControlName” which is a replacement of “ng-model” and it will take care of tracking and validations
A form group contains set of form controls which are grouped together, the group which we created here, is registrationForm, we can consider it as a form model
If you see below code we are using form builder to create a form group instance which is a registrationForm, the form builder creates instance for all input form controls, here, along with four form controls I am creating two more controls which are security question and answer and those are not tied to input form controls so I am assigning some default values to it, if you don’t assign default values then it will throw exception

import { Component, OnInit, Input } from '@angular/core';
import { RegistrationServiceService } from './registration-service.service';
import { User } from './User'
import { Router, ActivatedRoute } from '@angular/router';
import { Location} from '@angular/common';
import { FormBuilder, Validators,FormGroup,FormControl} from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css'],
export class RegistrationComponent implements OnInit {
  constructor(public fb: FormBuilder) { }
   public registrationForm ={
     firstName: ["", Validators.required],
     email: ["", Validators.required],
     password: ["", Validators.required],
     confirmPassword: ["", Validators.required],
     securityQuestion: ["Security Question", Validators.required],
     securityAnswer: ["Security Answer", Validators.required]
  ngOnInit() {
  submit(model: User, isValid: boolean) {
    console.log(model, isValid);
  let firstName = this.registrationForm.controls.firstName.value
  let email = this.registrationForm.controls.firstName.value
  let password1 = this.registrationForm.controls.securityQuestion.value

By default the Angular comes with OOTB Validation’s, those are required, minlength, maxlength and regex pattern, along with that we can write our own custom exceptions, I will cover in my next article how to write custom exceptions

Step 3 : Read Form Values

You can read form field values by using this syntax this.<form name>.controls.<form control name>.value

  let firstName = this.registrationForm.controls.firstName.value
  let email = this.registrationForm.controls.firstName.value
  let password1 = this.registrationForm.controls.securityQuestion.value

The isValid is an important that will tell you whether the form is valid or not, if it returns true then you can submit a form to the server otherwise display the error message to the end use, refer my other this article to get to know how to post data to the server which is using template driven forms to post data
Upon clicking of form submission if the form is valid then you will see isValid = true something like below, after security questions I am displaying the form status true or false

Download source code

[sociallocker] Template driven forms [/sociallocker]


By coderss

6 thought on “How to submit form to server in Angular 2”
  1. hi raj madalapu……….. this is madhavan…
    i want to read this article completely…. could read here only upto read values from angular2 form….rest not available… will you please send me the link to access it fully… thank you

Leave a Reply

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