Angular has vast library of modules so reactive form is one of the part of angular library.
Prerequisites knowledge:
- Angular
- HTML
- CSS
- Javascript
So, let’s start building a from .
Steps to create a reactive form in angular
- Create a new or existing angular project, you can also read this article to create new angular project.
- Create a component with ng generate command.
ng generate component helloworld
- 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'; @NgModule({ declarations: [ AppComponent, HelloworldComponent ], imports: [ BrowserModule, ReactiveFormsModule, AppRoutingModule ], 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'; @Component({ 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 console.log(this.form.value); } }
5. Edit HTML file, add attribute [formGroup] to form and formControlName to each input
<h1>Helloworld works!</h1> <form [formGroup]="form" (submit)="submitForm()"> <div> Name : <input type="name" formControlName="name" placeholder="Name" /> <br> </div> <div> Email : <input type="email" formControlName="email" placeholder="Email" /> <br> </div> <div> Password : <input type="password" formControlName="password" placeholder="Password" /> <br> </div> <div> <button type="submit">Submit</button> </div> </form>
Output :