Reactive Forms with Validations

First we need to add angular material to the project

ng add @angular/material

Create a module to handle all material imports and exports

ng g m material

Now follow the code below :

material.module.ts

import { NgModule } from '@angular/core';
import { MatButtonModule, MatInputModule, MatSelectModule, MatCheckboxModule, MatChipsModule} from '@angular/material';

const MaterialComponent = [
  MatButtonModule,
  MatInputModule,
  MatSelectModule,
  MatCheckboxModule,
  MatChipsModule
];

@NgModule({
  imports: [
    MaterialComponent
  ],
  exports: [
    MaterialComponent
  ]
})
export class MaterialModule { }

app.module.ts

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

import { AppComponet } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponet
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponet]
})
export class AppModule { }

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponet implements OnInit {
  myForm: FormGroup;
  success = false;

  constructor(private fb: FormBuilder){ }

  ngOnInit(): void {
    this.myForm = this.fb.group({
      email: ['', [
        Validators.required,
        Validators.email
      ]],
      message: ['', [
        Validators.required,
        Validators.minLength(5),
        Validators.pattern('[a-zA-Z]+')
      ]],
      age: ['', [
        Validators.required,
        Validators.minLength(2), //Minimum lengh of String is 2
        Validators.min(18),
        Validators.max(65)
      ]]
/*       agree: [false, [
        Validators.requiredTrue
      ]] */
    });
    this.myForm.valueChanges.subscribe(console.log);
  }

  get email() {
    return this.myForm.get('email');
  }
  get message() {
    return this.myForm.get('message');
  }
  get age() {
    return this.myForm.get('age');
  }

  submitForm(){
    this.success=true;
  }
}

app.component.html

<form [formGroup]="myForm" [hidden]="success" (ngSubmit)="submitForm()">
  Value: {{myForm.value | json}}
  <hr/>
  <mat-form-field>
    <input matInput placeholder="Email Id" formControlName="email"/>
    <mat-error *ngIf="email.invalid &amp;&amp; email.touched">
      Email id is inValid
    </mat-error>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Message" formControlName="message"/>
    <mat-error *ngIf="message.touched &amp;&amp; message.errors?.minlength">
      Minimum Length if 5
    </mat-error>
    <mat-error *ngIf="message.touched &amp;&amp; message.errors?.pattern">
      Invalid Pattern
    </mat-error>
    <mat-hint align="end">Must have one characters only</mat-hint>
  </mat-form-field>

  <mat-form-field>
    <input matInput formControlName="age" placeholder="Age"/>
    <mat-hint align="end">Enter your age</mat-hint>
    <mat-error *ngIf="age.touched &amp;&amp; age.errors?.required">
      This field is madatory
    </mat-error>
    <mat-error *ngIf="age.touched &amp;&amp; age.errors?.min">
      {{age.errors.min.actual}} you are too young to use this app kiddo!
    </mat-error>
    <mat-error *ngIf="age.touched &amp;&amp; age.errors?.max">
      {{age.errors.max.actual}} you are too old to use this app gramps!
    </mat-error>
  </mat-form-field><br/>
  <button type="submit" mat-raised-button [disabled]="myForm.invalid">Submit</button>
</form>
<div *ngIf="success" class="notification is-success">
  Yay! We received your submission
</div>

Output :

Leave a Comment