Angular 4 forms tutorial

I know you have to work on Angular 4 Forms that’s why you are here. So, without wasting a bit of time, I’m going to start this Angular 4 forms tutorial from scratch.

 

There are two ways to build forms in angular 4. First one is Template-Driven-Forms and second one is Reactive-Forms which share same @angular/forms library.

 

Let’s move ahead and learn how to work with Template-Driven-Forms and Reactive-Forms one by one.

 

How to work with Angular 4 Template-Driven-Forms

Template-Driven-Forms is an approach to create Angular 4 forms which are very similar to Angular 1. To getting started, we need to install a new Angular project. To do so, we will be using Angular CLI method. Use the following command.


ng new yourprojectname

 

Now, get into your project folder and run your angular project. Use following commands.


cd yourprojectname     //go to your project

ng serve                //run project

 

After installing project, we will import required library. In order to build Template-Driven-Forms, we need to import FormsModule library. To do so, head over to /src/app/app.module.ts and import FormsModule. See below example.


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

 

Next step is to create a form. In this Angular 4 forms tutorial, I am creating simple Bootstrap Form. To do so, head over to /src/app/app.component.html and insert following code.


<div class="col-md-6 col-md-offset-3">

<form #userForm = "ngForm" (ngSubmit)="onSubmit(userForm.value)">

<div class="form-group">

    <input type="name" placeholder=”Enter Your Name” name=”userName” ngModel>

  </div>


<div class="form-group">

    <input type="email" placeholder=”Enter Your Email” name=”email” ngModel>

  </div>

  <button type="submit" value=”submit”>Submit</button>

</form>

</div>

 

We are done with creating form template. In Template-Driven-Forms, we do most of the work in HTML. I have added some properties of Angular also. Let’s understand everything one by one.

 

We attach ngForm directive in form tag, which gives the value of all form input fields. In above example, I have added a ngForm directive in form tag and assigned a reference variable userForm to it, which represents the entire form. You can also say, we have an instance of ngForm assigned to userForm. I have also added a name to each input fields which is mandatory. And ngModel directive in every input field indicates that all form control belongs to this form ngForm directive.

 

I have also written a ngSubmit event and assigned a handler. Actually, when we click on submit button, this event is fired and capture the entire form values.

 

Note: It’s mandatory to give value=”submit” within button tag.

 

After creating form, go to /src/app/app.component.ts. Now we will call onSubmit function within AppComponent class and display data on browser console.


onSubmit(value: any){

  	console.log(value);

  }

or, you can also write


onSubmit = function(user){

console.log(user);

}

 

So, It was first part of this Angular 4 Forms tutorial, where we have learnt, how to work with Template-Driven-Forms . Now we will learn how to work with Reactive-Forms

 

How to Work With Angular 4 Reactive-Forms

It is also known as Model-Driven-Forms which is represented by a model which is responsible for handling users interaction within the form.

 

To create Angular 4 Reactive-Forms, we will install a new project again. Use the following command to install Angular project.


ng new yourprojectname

 

After that run the below commands.


cd yourprojectname

ng serve

 

In Reactive-Forms we import ReactiveFormsModule in root module of the application. In our case, root module is app.module.ts. So, head over to /src/app/app.module.ts and import ReactiveFormsModule from @angular/forms library and save it. After importing, your app.module.ts (root Module) should be like this:-


import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

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

import { HttpModule } from '@angular/http';
 
import { AppComponent } from './app.component';
 
@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    FormsModule,

    ReactiveFormsModule,

    HttpModule,

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

 

Next, we need to import some necessary classes. Go to /src/app/app.component.ts and import FormBuilder and FormGroup classes. See the following example.


import { FormBuilder, FormGroup } from '@angular/forms';

 

In Reactive-Forms, each form has instance assigned to FormGroup. We will also make an instance of FormGroup in this tutorial. And FormBuilder manages form control.

 

Next, add below codes within AppComponent class.


addressForm = new FormGroup({

  	name:           new FormControl(),

  	addressLine1:   new FormControl(),

  	addressLine2:   new FormControl(),

  	city:           new FormControl(),

  	country:        new FormControl(),

  	zip:            new FormControl(),
 
  });

 

Now we will build a form. Here I am using Bootstrap form. Go to /src/app/app.component.html and add below codes there.






<div class="col-md-6 col-md-offset-3">

<form [formGroup] = "addressForm" (ngSubmit) = "onSubmit()">

<div class="form-group">

	    <label for="name">Name:</label>

	    <input type="text" class="form-control" formControlName="name">

	  </div>


<div class="form-group">

	    <label for="address Line 1">Address Line 1:</label>

	    <input type="text" class="form-control" formControlName="addressLine1">

	  </div>


<div class="form-group">

	    <label for="address Line 2">Address Line 2:</label>

	    <input type="text" class="form-control" formControlName="addressLine2">

	  </div>


<div class="form-group">

	    <label for="city">City:</label>

	    <input type="text" class="form-control" formControlName="city">

	  </div>


<div class="form-group">

	    <label for="country">Country:</label>

	    <input type="text" class="form-control" formControlName="country">

	  </div>


<div class="form-group">

	    <label for="zip">Zip:</label>

	    <input type="text" class="form-control" formControlName="zip">

	  </div>

	  <button type="submit" class="btn primary" value="submit">Submit</button>

	</form>

</div>

 

Next, we will display input data on browser console. To do so look into /src/app/app.component.ts and add following script within AppComponent class.


onSubmit(){

  	console.log(this.addressForm.value);

  }

 

Now run this project in the browser and open developer console. Then, enter data in form inputs and click submit button. You will see all entered input data is rendering in the browser console. See below screenshot for the demo.

reactive forms output

 

How to Work With Angular 4 Forms Validations

Till now we have learned the two ways of creating Angular 4 Forms. It’s time to move on and take this Angular 4 forms tutorial to the next level. As you know, after creating a form, its validation is very important. So, we will learn, how to validate reactive forms in Angular 4.

 

Let’s start!

 

In order to validate Angular forms, first we need to import Validators library. To import, go to your applications /src/app/app.component.ts file and import Validators library. Refer below example.


import { FormGroup, FormControl, Validators } from '@angular/forms';

 

Next, we need to pass parameters to FormControl in AppComponent class. Go to /src/app/app.component.ts and pass validation parameters in FormControl. We are passing Validators.required here which will not allow users to left input fields blank. See below example.


 addressForm = new FormGroup({

  	name:           new FormControl("", Validators.required),

  	addressLine1:   new FormControl("", Validators.required),

  	addressLine2:   new FormControl("", Validators.required),

  	city:           new FormControl("", Validators.required),

  	country:        new FormControl("", Validators.required),

  	zip:            new FormControl("", Validators.required),

  });

 

Let’s go deeper and apply some more validation.

 

Now, I’m going to disable submit button until the user do not fill all the required input fields. Go to /src/app/app.component.html. And add [disabled] property in button tag with a condition. This will be disabled until the user does not enter all required fields. Refer below example.


<button [disabled] = "!addressForm.valid" type="submit" class="btn btn-primary" value="submit">Submit</button>

 

Once the user enters all required fields, the button will be enabled automatically.

You can also apply more validations. Such as min length, max length etc. See below example.


addressForm = new FormGroup({

  	name: new FormControl("", [Validators.required, Validators.minLength(4), 
 Validators.maxLength(10)]),

  	addressLine1:   new FormControl("", Validators.required),

  	addressLine2:   new FormControl("", Validators.required),

  	city:           new FormControl("", Validators.required),

  	country:        new FormControl("", Validators.required),

  	zip:            new FormControl("", Validators.required),

  });


 

In above example, I have applied two more validations (an array of validations). Where name input field should be entered minimum 4 character and maximum 10. The button will be disabled till entering 4 characters. The button will be disabled automatically if you enter more than 10 characters.

 

It’s time to think one level up!

 

What if, you need to display an error message.

 

How to Display Angular 4 Forms Error Message

In order to validate forms, we often display an error message if users do not enter valid inputs. So, here I’m going to display the error message. Go to /src/app/app.component.html and follow below code.




<div class="col-md-5">

<form [formGroup] = "addressForm" (ngSubmit) = "onSubmit()">

<div class="form-group">

       <label for="name">Name:</label>

       <input type="text" class="form-control" formControlName="name">

        
<div *ngIf="addressForm.controls['name'].hasError('required')" class="alert alert-danger">


This field is required


        </div>


<div *ngIf="addressForm.controls['name'].hasError('minlength')" class="alert alert-danger">


Please Enter atleat 4 character


	</div>


<div *ngIf="addressForm.controls['name'].hasError('maxlength')" class="alert alert-danger">


You can not enter more than 10 characters


	</div>


     </div>


<div class="form-group">

	<label for="address Line 1">Address Line 1:</label>

	<input type="text" class="form-control" formControlName="addressLine1">

	
<div *ngIf="addressForm.controls['addressLine1'].hasError('required')" class="alert alert-danger">


This field is required


	</div>


<div *ngIf="addressForm.controls['addressLine1'].hasError('minlength')" class="alert alert-danger">


Please Enter atleat 4 character


	</div>


<div *ngIf="addressForm.controls['addressLine1'].hasError('maxlength')" class="alert alert-danger">


You can not enter more than 10 characters


	 </div>


    </div>


<div class="form-group">

	<label for="address Line 2">Address Line 2:</label>

	<input type="text" class="form-control" formControlName="addressLine2">

	
<div *ngIf="addressForm.controls['addressLine2'].hasError('required')" class="alert alert-danger">


This field is required


	</div>


<div *ngIf="addressForm.controls['addressLine2'].hasError('minlength')" class="alert alert-danger">


Please Enter atleat 4 character


	</div>


<div *ngIf="addressForm.controls['addressLine2'].hasError('maxlength')" class="alert alert-danger">


You can not enter more than 10 characters


	 </div>


    </div>


<div class="form-group">

	<label for="city">City:</label>

	<input type="text" class="form-control" formControlName="city">

	
<div *ngIf="addressForm.controls['city'].hasError('required')" class="alert alert-danger">


This field is required


	 </div>


<div *ngIf="addressForm.controls['city'].hasError('minlength')" class="alert alert-danger">


Please Enter atleat 4 character


	 </div>


<div *ngIf="addressForm.controls['city'].hasError('maxlength')" class="alert alert-danger">


You can not enter more than 10 characters


	 </div>


     </div>


<div class="form-group">

	 <label for="country">Country:</label>

	 <input type="text" class="form-control" formControlName="country">

	 
<div *ngIf="addressForm.controls['country'].hasError('required')" class="alert alert-danger">


This field is required


	  </div>


<div *ngIf="addressForm.controls['country'].hasError('minlength')" class="alert alert-danger">


Please Enter atleat 4 character


	  </div>


<div *ngIf="addressForm.controls['country'].hasError('maxlength')" class="alert alert-danger">


You can not enter more than 10 characters


	   </div>


      </div>


    </div>


<div class="form-group">

	    <label for="zip">Zip:</label>

	    <input type="text" class="form-control" formControlName="zip">

      </div>


     <button [disabled] = "!addressForm.valid" type="submit" class="btn btn-primary" value="submit">Submit</button>

   </form>

</div>



 

Final Words

So, it was Angular 4 forms tutorial. Hope this will help you to a lot. If you have any query, do comment and  join us on Facebook, Twitter, and LinkedIn for more updates.