×
☰ See All Chapters

Angular Reactive Forms Example

In reactive forms all changes to the form and the component are managed in code using instances of FormGroup and FormControls. Below is an example for how we can manage the forms using instances of FormGroup and FormControls. To use these FormGroup and FormControls classes, an application's module needs to import ReactiveFormsModule from @angular/forms. Also, ReactiveFormsModule must be included in the imports array of the module's @NgModule decorator.

app.component.ts

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

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

 

@Component({

selector: 'app-tag',

template: `

 

<form [formGroup]='group' (ngSubmit)='handleSubmit()'>

 

  First Name:<input formControlName='firstName'><br /><br />

 

  Last Name:<input formControlName='lastName'><br /><br />

 

  <input type='button' (click)='changeFirstNameToUpperCase()' value='Change First Name To Uppercase'><br />

 

  <input type='button' (click)='changeLastNameToUpperCase()' value='Change Last Name To Uppercase'><br />

 

  <input type='submit' value='Submit'>

 

</form>

`})

 

export class AppComponent {

  public group: FormGroup;

  constructor() {

    this.group = new FormGroup({

      'firstName': new FormControl('Manu'),

      'lastName': new FormControl('Manjunatha')

    });

  }

 

  public changeFirstNameToUpperCase() {

    const control = this.group.get('firstName');

    control.setValue(control.value.toUpperCase());

  }

 

  public changeLastNameToUpperCase() {

    const control = this.group.get('lastName');

    control.setValue(control.value.toUpperCase());

  }

 

  public handleSubmit() {

    alert('Form submitted');

  };

}

app.module.ts

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

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

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

 

import { AppComponent } from './app.component';

 

@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    ReactiveFormsModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

index.html

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Angular Example</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

</head>

<body>

  <app-tag></app-tag>

</body>

</html>

Project directory structure

angular-reactive-forms-example-0

Output

angular-reactive-forms-example-1
 

All Chapters
Author