无法读取无效反应形式的属性“电子邮件”

时间:2019-02-12 17:11:57

标签: angular

如果电子邮件无效并且registerForm.controls.email.errors.email给我带来一些问题,我已经设置了验证器。它无法正常工作,当我在该电子邮件字段中输入电子邮件然后查看控制台时,我看到错误无法读取属性为null的电子邮件。

   <div *ngIf="loading" id="overlay"><div class="loader"></div></div>
          <form method="post" [formGroup]="registerForm" (ngSubmit)="onSubmit()">
            <div id="tab-2" class="log-tab-content">


                <div class="login-left">

                  <div class="clearfix"></div>

                  <div *ngIf="registerForm.controls.email.errors.email" data-tip="Email must be a valid email address"></div>
                  <input type="text"  formControlName="email" name="email" placeholder="Email *" tabindex="3"/>
                  <div class="clearfix"></div>

                  <br>

                  </div>
                <div class="clearfix"></div>
                <button type="submit" class="log-button log-button1">Register now</button>
              </div>

          </form>

ts文件

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { DataService } from '../services/data.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

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


  registerForm: FormGroup;


  constructor(private reg: AuthService, private data: DataService, private formBuilder: FormBuilder) {
   }


  ngOnInit() {


    this.registerForm = this.formBuilder.group({

      email: ["", [Validators.required, Validators.email]],

    })

  }


  onSubmit() {


}

}

1 个答案:

答案 0 :(得分:0)

方法1。

使用hasError方法检查表单控制错误

<div *ngIf="registerForm.controls.email.hasError('email')" 
          data-tip="Email must be a valid email address"></div>

方法2。

使用safe navigation (?.)

<div *ngIf="registerForm.controls.email.errors?.email" 
          data-tip="Email must be a valid email address"></div>