异步自定义验证会导致控制台出错:“无法在Object.eval [作为updateDirectives]读取null'属性''

时间:2017-08-01 07:27:09

标签: angular validation typescript

目前,我正在通过MaximilianSchwarzmüllerAngular4教程进行反应形式的分配。在作业中,我必须创建一个反应形式,我做了。然后我不得不创建一个自定义异步验证器,它检查控件的值。它不应该等于'测试'。这是我的打字稿代码:

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

import {Observable} from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  statuses = ['Stable', 'Critical', 'Finished'];
  signupForm: FormGroup;

  ngOnInit() {
    this.signupForm = new FormGroup({
      'projectName': new FormControl(null, [Validators.required], this.forbiddenName),
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'projectStatus': new FormControl('Stable')
    });
  }

  onSubmit() {
    console.log(this.signupForm.value);
    console.log(this.signupForm);
  }

  forbiddenName(control: FormControl): Promise<any> | Observable<any> {
    const promise = new Promise<any>((resolve, reject) => {
      setTimeout(() => {
        if (control.value === 'Test') {
          resolve({'projectNameIsForbidden': true});
        } else {
          resolve(null);
        }
      }, 2000);
    });
    return promise;
  }

}

这是我的HTML:

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
          <label for="project-name">Project name</label>
          <input type="text" id="project-name" class="form-control" formControlName="projectName">
          <div class="help-block" *ngIf="!signupForm.get('projectName').valid && signupForm.get('projectName').touched">
            <span *ngIf="signupForm.get('projectName').errors['required']">Can't be empty!<br></span>

            <span *ngIf="signupForm.get('projectName').errors['projectNameIsForbidden']">This name is forbidden!</span>
          </div>
        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input type="email" id="email" class="form-control" formControlName="email">
          <div class="help-block" *ngIf="!signupForm.get('email').valid && signupForm.get('email').touched">
            <span *ngIf="signupForm.get('email').errors['required']">Can't be blank!<br></span>
            <span *ngIf="signupForm.get('email').errors['email']">Has invalid format!</span>
          </div>
        </div>
        <div class="form-group">
          <label for="project-status">Project Status</label>
          <select id="project-status" class="form-control" formControlName="projectStatus">
            <option *ngFor="let status of statuses">{{ status }}</option>
          </select>
        </div>
        <button class="btn btn-success" type="submit">Submit</button>
      </form>
    </div>
  </div>
</div>

它似乎运行正常,它在我的视图中给出了相应的错误消息,但在控制台中,我在projectName控件中的每个keydown都收到错误。这是错误:

enter image description here

那么,错误出现的原因是什么?谢谢。

1 个答案:

答案 0 :(得分:46)

错误原因在于:

<span *ngIf="signupForm.get('projectName').errors['required']">
   Can't be empty!
</span>

当您输入errors变为null时,如果您在异步验证程序进行评估之前从字段移动,errors将为null,因此Angular无法读取它。这可以使用安全导航操作员来解决:

<span *ngIf="signupForm.get('projectName').errors?.required">

但由于我更喜欢​​使用hasError来显示消息,因此我会将这两种验证更改为:

<span *ngIf="signupForm.hasError('projectNameIsForbidden', 'projectName')">
<span *ngIf="signupForm.hasError('required', 'projectName')">