Search code examples
angularvalidationangular-materialmobx-react-form

Angular Material (8) Error Message (from Validator) being displayed when Page reloaded


I am new to Angular Material. I am working on a Registration form using Angular Material (8). When doing so, I am seeing that the Error Message is displayed when the page is Reloaded (by hitting the "Refresh" Button on the browser). The field is never touched in any way, shape or form.

enter image description here

Why is this the case?

TIA

File: register.component.html

[ ... snip ...]

       <div class="flex-register-form">

            <!-- Form -->
            <form [formGroup]="registerForm" (ngSubmit)="registerForm.valid && onSubmit()" class="text-center">

                <div class="form-col">
                    <div class="col">
                        <!-- First name -->
                        <div class="md-form">
                            <input required type="text" id="materialRegisterFormFirstName" class="form-control" mdbInput
                                formControlName="firstname" />
                            <label for="materialRegisterFormFirstName">First name</label>
                            <mat-error *ngIf="registerForm.controls['firstname'].hasError('required')" >First name is required</mat-error>
                        </div>

[ ... snip ...]

File: register.component.ts

import { Component, OnInit } from '@angular/core';
import { RegisterModel } from '../../models/register.models';
import {  FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';


@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})

export class RegisterComponent implements OnInit {

  user: RegisterModel = new RegisterModel();
  registerForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.registerForm = new FormGroup({
      'firstname': new FormControl(null, [Validators.required]),
      'lastname': new FormControl(null, [Validators.required, Validators.maxLength(25)]),
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.maxLength(25)]),
      'password': new FormControl(null, [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
      'agree': new FormControl(null, [Validators.required])
    });
  }

  onSubmit() {
    console.log(" was submited ");
  }

}

Solution

  • It's because as per Validation it is pending. But, we haven't touched the control yet so what we can do is that we can check whether the user interacted with the control or not by checking the control status touched of the form field.

    Correction

    <mat-error *ngIf="registerForm.controls['firstname'].hasError('required') && registerForm.controls.firstname.touched" >First name is required</mat-error>
    

    You can read more about it here