Complete Reactive Form Angular

 

In this tutorial we going to learn how to use angular reactive form in our angular application 

reactive form is really amazing and has many feature and good code maintains approach and increase development work fast.

How to import angular reactive form in our application 

1. In app.module.ts file import reactive module in imports array of ngModule decorator. this will me reactive module available to your project if you have modular approach then import this on module level of specific feature

Let's start create and example and start using reactive form 

In this example we will coverup all necessary input fields in a web form and validations

- input 

- checkbox

Demo

Import the Reactive forms Module in angular
app.module.ts
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule
  ],
})
export class AppModule { }

Write Css for make this demo appearing is a bit good 
demo-form.component.css
form {
    background: #edffd9;
    padding: 1%;
    width: 50%;
    overflow: hidden;
    border-radius: 6px;
    margin-bottom: 18px;
    margin-left: 23%;
    margin-top: 35px;
}

input.txt {
    width: 96%;
    padding: 2%;
    margin: 6px 0px;
    outline-color: #e8e7e7;
    border: 1px solid #e2e2e2;
}

.error {
    color: #e64c4c;
    font-size: 12px;
    font-family: sans-serif,monospace;
}

.t-and-c {
    margin: 5px 0px;
    font-size: 14px;
    font-family: sans-serif;
}

button {
    background: #85b54e;
    color: #f1f1f1;
    border: 0px;
    border-radius: 3px;
    margin: 3px 0px;
    padding: 7px;
    margin-right: 1%;
    font-size: 16px;
}

Write the html code for reactive and bind reactive form objects.
demo-form.component.html 
<form [formGroup]="form" (ngSubmit)="submitForm(form)">
        <input type="text" class="txt" placeholder="enter full name" formControlName="fullName" /><br />
        <div *ngFor="let validation of validation_messages.fullName" class="error">
            <ng-container *ngIf="form.get('fullName').hasError(validation.type) 
                       && (form.get('fullName').dirty || form.get('fullName').touched)">
                {{validation.message}}</ng-container>
        </div>
        <input type="email" class="txt" formControlName="email" placeholder="enter email">
        <div *ngFor="let validation of validation_messages.email" class="error">
            <ng-container *ngIf="form.get('email').hasError(validation.type) 
                       && (form.get('email').dirty || form.get('email').touched)">
                {{validation.message}}</ng-container>
        </div>
        <div class="t-and-c">
            <label>T&C</label>
            <input type="checkbox" formControlName="isTerm" value="false" /><br />
            <div *ngFor="let validation of validation_messages.isTerm" class="error">
                <ng-container *ngIf="form.get('isTerm').hasError(validation.type) 
                           && (form.get('isTerm').dirty || form.get('isTerm').touched)">
                    {{validation.message}}</ng-container>
            </div>
        </div>
        <button type="submit">submit</button>
    </form>


Now lets write the code in ts file and submit the form , so we using reactive form so we need to import reactive form exports like 
FormGroup
FormBuilder
Validators
FormControl

demo-form.component.ts
import { FormGroup, FormBuilder, Validators, FormControl} from '@angular/forms';
@Component({
  selector: 'app-demo-form',
  templateUrl: './demo-form.component.html',
  styleUrls: ['./demo-form.component.scss']
})
export class demoFormComponent implements OnInit {

formFormGroup;
validation_messages = {
    fullName: [
      { type: 'required', message: 'Full name is required' },
      { type: 'minlength', message: 'minimum length is 2' },
    ],
    cofname: [
      { type: 'required', message: 'Conference name is required' },
      { type: 'minlength', message: 'minimum length is 2' },
    ]
  };

  constructor(private formBuilderFormBuilder) { }
//angular initialize
  ngOnInit() {
    this.initForm();
  }

//initialize reactive form
  initForm() {
    this.form = this.formBuilder.group({
      fullName: ['', [
        Validators.required,
        Validators.minLength(2)
      ]],
      email: new FormControl('', {
        validators: Validators.compose([
          Validators.required,
          Validators.email
        ]),
        updateOn: 'change'
      }),
      isTerm: new FormControl(false, {
        validators: Validators.compose([
          Validators.requiredTrue
        ]),
        updateOn: 'change'
      })
    })
  }
  
//submit reactive form
  submitForm(formFormGroup) {
    if (form.valid{
        let strForm = JSON.stringify(form.value,null,4);
          alert(strForm)
    }
    else {
      this.form.markAllAsTouched();
    }
  }


}
To use this project just create angular project and copy and paste code in your respective file given in above 

Sample Images of demo's



Show validation messages



Adding information  and submit the form 




Show result on submit 


Comment below if need any improvement or any query

Comments