Angular 5自定义验证显示异常

时间:2017-12-24 04:18:12

标签: angular angular5

我正在研究Angular 5反应形式,并尝试制作一个示例自定义验证器,在表单上显示错误消息。当我尝试在项目名称字段中键入任何内容时(称为" namey"此处),我得到此异常(给出的行号仅指向HTML中输入的开头):

AppComponent.html:20 ERROR TypeError: Cannot read property 'cannotBeTestx' of null
at Object.eval [as updateDirectives] (AppComponent.html:27)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14338)
at checkAndUpdateView (core.js:13507)
at callViewAction (core.js:13857)
at execComponentViewsAction (core.js:13789)
at checkAndUpdateView (core.js:13513)
at callWithDebugContext (core.js:14739)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14276)
at ViewRef_.detectChanges (core.js:11299)
at eval (core.js:5783)

以下是组件代码:

ngOnInit() {
  this.projectForm = new FormGroup({
    namey: new FormControl(null, [Validators.required, this.cannotBeTest1]),
    email: new FormControl(null, [Validators.required, Validators.email]),
    status: new FormControl('1')
  });
}

以下是自定义验证码:

cannotBeTest1(control: FormControl): {[s: string]: boolean} {
  const name: string = control.value;
  if (name && name.toLowerCase() === 'test') {
    return {'cannotBeTestx': true};
  } else {
    return null;
  }
}

以下是此元素的HTML(还有一些其他表单元素正常工作,之后是结束表单标记):

<form class="ui form-vertical" [formGroup]="projectForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="project-name">project Name</label>
      <input
        class="form-control"
        type="text"
        id="project-name"
        placeholder="Enter project name"
        formControlName="namey"
      />
      <span class="help-block" *ngIf="projectForm.get('namey').errors['cannotBeTestx'] && (projectForm.get('namey').touched || formSubmitted)">-->
        please enter a valid project name
      </span>
      <span class="help-block" *ngIf="!projectForm.get('namey').valid && (projectForm.get('namey').touched || formSubmitted)">
        please enter a project name
      </span>
    </div>

我一直在搞乱事情,重命名东西,然后归结为错误显示的这一部分是问题:

projectForm.get('namey').errors['cannotBeTestx']

有趣的是,如果我删除HTML中显示的错误消息,则自定义验证器可以正常工作(我无法生成项目名称&#34; test&#34;)并且我得到另一个通用错误消息显示。所以它似乎是关于我检查自定义验证器是否无效的方式,但我不能为我的生活弄清楚它是什么。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

试试这个

<span class="help-block" *ngIf="projectForm.controls['namey'].hasError['cannotBeTestx'] && (projectForm.controls['namey'].touched || formSubmitted)">

<span class="help-block" *ngIf="!projectForm.controls['namey'].valid && (projectForm.controls['namey'].touched || formSubmitted)">