How to show different validation messages for email validation in Angular2 using Validators class?

冷暖自知 提交于 2019-12-06 09:12:50
import { Component } from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
  <input [formControl]="ctrl" />

  <div *ngIf="ctrl.errors?.email">
    Provided email is not a valid email
  </div>

  <div *ngIf="ctrl.errors?.required">
    Please provide an email address
  </div>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  ctrl = new FormControl(null, Validators.compose([Validators.email, Validators.required]));
}

Live demo

Discussion in the comments proved that the answer to this specific problem is:

<div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('email')">Provide a valid email.</div>
<div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('required')">Please provide an email address</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!