Spread the love

Angular has vast library of modules so reactive form is one of the part of angular library.

Prerequisites knowledge:

  1. Angular
  2. HTML
  3. CSS
  4. Javascript

So, let’s start building a from .

Steps to create a reactive form in angular

  1. Create a new or existing angular project, you can also read this article to create new angular project.
  2. Create a component with ng generate command.

    ng generate component helloworld

    ng generate component
  3. Import ReactiveFormsModule module add it in to import block.
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HelloworldComponent } from './helloworld/helloworld.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

4. Edit helloworld.component.ts and import FormGroup and FromControl from @angular/form

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

  selector: 'app-helloworld',
  templateUrl: './helloworld.component.html',
  styleUrls: ['./helloworld.component.css']
export class HelloworldComponent implements OnInit {

  form: FormGroup = new FormGroup(
        name:new FormControl("inital value ",[Validators.required]),
        email:new FormControl("inital value ",[Validators.required]),
        password:new FormControl("",[Validators.required]),
    ); // creating a form group
  constructor() { }

  ngOnInit(): void {


  submitForm(){ //handle the form after submit




5. Edit HTML file, add attribute [formGroup] to form and formControlName to each input

<h1>Helloworld works!</h1>
<form [formGroup]="form" (submit)="submitForm()">
    Name : <input type="name" formControlName="name" placeholder="Name"  /> <br>
    Email : <input type="email" formControlName="email"  placeholder="Email" /> <br>
    Password : <input type="password" formControlName="password"  placeholder="Password" /> <br>
    <button type="submit">Submit</button>


Output :

Reactive form with submit
You can also read about  How to upload multiple files and form in angular 12 reactive form

Leave a Reply