Wednesday, September 30, 2020

Angular Reactive Form Example

In this post we’ll see how to create a reactive form in Angular.

Importing ReactiveFormsModule

You need to import ReactiveFormsModule into the AppModule (app.module.ts) for Angular Reactive form to work.

Add ReactiveFormsModule in the imports section of the AppModule.

imports: [

Angular Reactive Form example

In the example we’ll create a form with two input fields for name and email, a date picker for picking date and a drop down to select one of the option. Once finsihed our form should look something like this-

Angular Reactive Form Example

Data Model

Member class defines the data model reflected in the form.


export class Member {
  name: string;
  mail: string;
  membershipDate: Date;
  membershipType: string;
  constructor(name: string, mail: string, membershipDate: Date, membershipType: string) { = name;
    this.mail = mail;
    this.membershipDate  = membershipDate;
    this.membershipType = membershipType;

Component class (app.component.ts)

In ReactiveForm you create the form controls in your code so Component class is the appropriate place to create such controls which you will sync up with the corresponding template.

In Angular form a FormControl represents an individual form control where as FormGroup represents a collection of form controls as a group. So, it is obvious that in your code you will create a FormGroup object and with in that you will add form controls corresponding to fields in the form.

import { DatePipe } from '@angular/common';
import { Component, OnInit} from '@angular/core';
import { FormControl, FormGroup} from '@angular/forms';
import { Member } from './member.model';

  selector: 'app-root',
  templateUrl: './app.component.html', 
  providers: [DatePipe]
export class AppComponent implements OnInit {
  membershiptypes = ['Silver', 'Gold', 'Platinum'];
  currentDate = new Date();
  member = new Member('', '', new Date(), '');
  submitted = false;
  membershipForm : FormGroup;
  constructor(private datePipe: DatePipe){ }
  ngOnInit() {
    this.membershipForm = new FormGroup({
      memberName: new FormControl(null),
      email: new FormControl(null),
      mdate: new FormControl(this.datePipe.transform(this.currentDate, 'yyyy-MM-dd')),
      membershipType: new FormControl('Silver')
    this.submitted = true; = this.membershipForm.value.memberName;
    this.member.mail =;
    this.member.membershipDate = this.membershipForm.value.mdate;
    this.member.membershipType = this.membershipForm.value.membershipType; 

Important points to note here are-

1. You need to import FormControl and FormGroup classes.

2. A reference to FormGroup is created named membershipForm.

3. Using that reference a new FormGroup object is created and an array of form controls are added to that FormGroup object.

4. A FromControl takes three arguments state, Validator and AsyncValidator. In this example we are not going into validation so we’ll pass just one argument. For name and email initial value is passed as null. For date current date is passed as default and for Membership type ‘Silver’ is passed as default.

5. onSubmit() method is called when the form is submitted and the values entered in the form are used to create an object of Member class.

Template (app.component.html)

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8">
      <h1>Membership Form</h1>
      <form [formGroup]="membershipForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" id="name"
        <div class="form-group">
          <label for="email">email</label>
          <input type="email" class="form-control" id="email"
        <div class="form-group">
          <label for="mdate">Membership Date</label>
          <input type="date" class="form-control" id="mdate"
        <div class="form-group">
          <label for="type">Membership Type</label>
          <select class="form-control" id="type"                    
            <option *ngFor="let mtype of membershiptypes" [value]="mtype">{{mtype}}</option>
        <button type="submit" class="btn btn-success">Submit</button>
  <div *ngIf="submitted">
    <div class="row">
      <div class="col-xs-12 col-sm-10 col-md-8">
        <p>Name: {{}}</p>
        <p>email: {{member.mail}}</p>
        <p>Membership Date: {{member.membershipDate | date:'dd/MM/yyyy'}}</p>
        <p>Membership Type: {{member.membershipType}}</p>

Important points to note here are-

1. You need to tell the template, from where it has to get all the FormControls for the form, that is done by binding the FormGroup reference.

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

2. For syncing up the form controls you will have to bind each form field with the form control created in the component. That is done by assigning formControlName to the name given in the component.

<input type="text" class="form-control" id="name"

3. For Membership Type dropdown, options are added using ngFor which iterates over an array called membershiptyes defined in the Component class.

4. Submit button is of type submit so it will trigger a submit event for that event binding is done at the form level.

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

5. There is another row which just displays the entered values.

Reactive form creation

That's all for this topic Angular Reactive Form Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page

Related Topics

  1. Angular Reactive Form Validation Example
  2. Angular Template-Driven Form Validation Example
  3. FormGroup in Angular With Examples
  4. FormArray in Angular With Example
  5. Radio Button in Angular Form Example

You may also like-

  1. Angular ngIf Directive With Examples
  2. Angular Cross Component Communication Using Subject Observable
  3. Setting and Fetching Route Parameters in Angular
  4. Angular Custom Two-Way Data Binding
  5. Java CyclicBarrier With Examples
  6. this Keyword in Java With Examples
  7. Java Multithreading Tutorial
  8. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example

No comments:

Post a Comment