DEV Community

Cover image for Reactive Forms And Form Validation In Angular With Example
Robert Look
Robert Look

Posted on

Reactive Forms And Form Validation In Angular With Example

This tutorial we are learn how to create Reactive Forms And Form Validation In Angular With Example very simply form see below:
provides a model-driven approach to handling form inputs value change over time. In this form reactive form, we need to import "ReactiveFormsModule" from the angular forms library. We will use FormControl, FormGroup, FormArray, Validation class with Reactive forms in angular.

Reactive Forms And Form Validation In Angular With Example

src/app/app.component.html

<h1>Reactive Forms And Form Validation In Angular With Example - phpcodingstuff.com</h1>

<form [formGroup]="form" (ngSubmit)="submit()">

    <div class="form-group">
        <label for="name">Name</label>
        <input formControlName="name" id="name" type="text" class="form-control">
        <span *ngIf="form.name.touched && form.name.invalid" class="text-danger">Name is required.</span>
    </div>

    <div class="form-group">
        <label for="email">Email</label>
        <input formControlName="email" id="email" type="text"  class="form-control">
        <span *ngIf="form.email.touched && form.email.invalid" class="text-danger">Email is required.</span>
    </div>

    <div class="form-group">
        <label for="body">Body</label>
        <textarea formControlName="body" id="body" type="text" class="form-control">  </textarea>
          <span *ngIf="form.body.touched && form.body.invalid" class="text-danger">Body is required.</span>
    </div>

    <button class="btn btn-primary" type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

src/app/app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';     // <----------------- This code---------------

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor() { }

  ngOnInit(): void {

  }

  form = new FormGroup({
    name: new FormControl('', Validators.required),
    email: new FormControl('', Validators.required),
    body: new FormControl('', Validators.required)
  });


  submit(){
    console.log(this.form.value);
  }

}
Enter fullscreen mode Exit fullscreen mode

Original source : https://www.phpcodingstuff.com/blog/reactive-forms-and-form-validation-in-angular-with-example.html

Top comments (0)