How to create a form in angular

In this tutorial we will learn how to create a form in angular 7 application. We will make a form like below.

angular-form-contact-form

Before we head to create the form, let’s understand the basics:

There are 2 types of forms :
1. Template driven forms
2. Model driven or Reactive forms 

1. Template driven forms

The template driven approach makes use of built-in directives to build forms such as ngModelngModelGroup, and ngForm available from the FormsModule module.

When to use ?

  • where forms are small
  • Simple validations
  • migrating from angular 1 to angular 2

Advantage:

  • easier to create
  • less code

2. Model driven or Reactive forms

The model driven approach of creating forms in Angular 6 makes use of FormControlFormGroup and FormBuilder available from the ReactiveFormsModule module.

When to use ?

  • Where forms are big
  • validations are complex

Reactive forms have majorily two classes:

  • FormGroup : can be considered as a collection of FormControls and other FormGroups
  • FormControl : to bind the properties with the html elements

At first, we will create an instance of FormGroup class and link it to the html form. Then, we will create a number of instances of FormControl as many number of form elements.

Let’s Begin !

Step 1: Registering the reactive forms module in app.module.ts

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

and

 imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule ], 

Step 2: Creating a FormGroup in app.component.ts

import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  title = 'my-dream-app';
  contactForm : FormGroup;
  
  constructor(){}
  ngOnInit(){
    this.contactForm = new FormGroup({
      name: new FormControl(),
      email: new FormControl()
    });
  }
  
  onSubmit(): void{
    console.log(this.contactForm.value);
  }
}

we will print the values entered in the form to the console log.

Step 3: Associating FormGroup with the HTML view

<div class="col-lg-4" >
  <form [formGroup]="contactForm" (ngSubmit)="onSubmit()" class="form-horizontal">
    <h3 class="panel-title">Contact Form</h3>
    <div class="form-group">
      <label>Name</label>
      <input id="name" formControlName="name" type="text" class="form-control">
    </div>
    <div class="form-group">
      <label>Email</label>
      <input id="email" formControlName="email" type="text" class="form-control">
    </div>
    <div>
      <button type="submit" class="btn-primary">Submit</button>
    </div>
  </form>
</div>

Output

angular-form-contact-form-output

Summary

In this tutorial, we learnt about how to create a form in angular application and different types of form.
Hope you liked it!


Leave a Comment