如何获得所需的错误和电子邮件模式分别角4?

时间:2017-10-11 00:40:09

标签: angular angular-reactive-forms

我正在实施角度4反应形式验证。我有这种形式的布局

enter image description here

这是我的app.component.ts代码

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

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

 rForm     : FormGroup;
 post      : any;
 name      : string ='';
 userEmail : string = '';
 desc      : string ='';
 titleAlert: string ='This is required';
 emailError: string ="Enter valid email";

constructor(private fb : FormBuilder){
  this.rForm = fb.group({
    'name' : [null, Validators.required],
    'userEmail' : [null, Validators.email],
    'desc' : [null, Validators.compose([Validators.required, 
Validators.minLength(30), Validators.maxLength(500)])],
    'validate' :'' 
  });
 }

addPost(post){
    this.desc = post.desc;
    this.name = post.name;
 }

}

这是我的app.component.hmtl代码

<div *ngIf="!name;else formInfo">
<form [formGroup]="rForm" (ngSubmit)="addPost(rForm.value)">
<div class="form-container">
  <div class="row columns">

    <h1>My Reactive Form</h1>

    <label>Name
      <input type="text" formControlName="name">
    </label>
    <div class="alert" *ngIf="!rForm.controls['name'].valid && 
    rForm.controls['name'].touched">{{titleAlert}}</div>

    <label>Email
        <input type="text" formControlName="userEmail">
      </label>
      <div class="alert" *ngIf="!rForm.controls['userEmail'].valid && 
      rForm.controls['userEmail'].touched">{{emailError}}</div>

      <label>Description
        <input type="text" formControlName="desc">
    </label>
    <div class="alert" *ngIf="!rForm.controls['desc'].valid && 
    rForm.controls['desc'].touched">Description should be between 30 to 50 
    characters.</div>

      <label for="validate">Minimum of 3 characters</label>
      <input type="checkbox" name="validate" formControlName="name" 
    value="1">On
      <input type="submit" class="button expanded" value="Submit Form" 
        [disabled]="!rForm.valid">
    </div>      
  </div>
  </form>
 </div>

 <ng-template #formInfo>
  <div class="form-container">
    <div class="row columns">
      <h1>{{name}}</h1>

      <p>{{desc}}</p>
  </div>
 </div>
</ng-template>

我希望当用户在电子邮件输入中键入电子邮件时,如果它写错了电子邮件,那么我应该得到单独的错误,如“输入有效的电子邮件”,如果用户将电子邮件输入留空并跳转到另一个字段,那么我应该得到像“这个字段是必需的”这样的错误我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

hasError我相信会奏效。

*ngIf="!rForm.controls['userEmail'].hasError('required')

参见示例:https://material.angular.io/components/input/overview#error-messages