Angular 8 mat-error not displaying error message

421 views Asked by At

I have borrowed the following code from one of my older projects in which it worked fine. But now it does not display any error message as I have used the same code in the new project.

HTML

<mat-card class="centered card">
<form [formGroup]="loginForm"> 
    <mat-form-field appearance='outline'>
        <mat-label>Email</mat-label>
        <input matInput fromControlName="email" type="email" placeholder="Email"/>
        <mat-error>
            <div *ngIf="loginForm.get('email').hasError('pattern')">Enter valid Email ID</div>
            <div *ngIf="loginForm.get('email').hasError('required')">Email is required</div>
        </mat-error>
    </mat-form-field>
    <br>
    <mat-form-field appearance='outline'>
        <mat-label>Password</mat-label>
        <input matInput fromControlName="pass" type="pass" placeholder="Password"/>
        <mat-error>
            <div *ngIf="loginForm.get('pass').hasError('required')">Password is required</div>
        </mat-error>
    </mat-form-field>
    <br>
    <mat-card-actions>
        <button mat-raised-button class="full-width" (click)="auth()">Login</button>
    </mat-card-actions>
</form>
</mat-card>

TYPESCRIPT

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

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

    loginForm: FormGroup;
    userEmail: FormControl;
    userPass: FormControl;

    constructor() { }

    ngOnInit() {
      this.userEmail = new FormControl('', Validators.compose(
          [Validators.required, Validators.pattern(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,63})$/)]
      ));
      this.userPass = new FormControl('', Validators.required);
      this.loginForm = new FormGroup({
        email: this.userEmail,
        pass: this.userPass
      });
    }

    auth(event){
      console.log(event);
    }

}

This code used to work as expected before. I wanted to display different message for different cases of validation failures.

1

There are 1 answers

2
julianobrasil On BEST ANSWER

It seems to be a simple typo: instead of fromControlName, change it to formControlName