繁体   English   中英

Angular:无法读取 null 的属性(读取“cannotContainSpace”)

[英]Angular: Cannot read properties of null (reading 'cannotContainSpace')

我在 Angular 中创建了自定义 ValidationFn。不知何故,我总是收到以下错误消息:

错误类型错误:无法在 TutorRegistrationComponent_Template (template.html:31) 在 refreshComponent (core.js:9414) 在 refreshView (core.js:9414) 在 executeTemplate (core.js:9414) 读取属性在 refreshChildComponents (core.js:9211) 在 refreshView (core.js:9464) 在 renderComponentOrTemplate (core.js:9528) 在 tickRootContext (core.js:10754) 在 detectChangesInRootView (core.js:10779) 在 RootViewRef.detectChanges (核心.js:22792)

这就是我制作验证器的方式:

export class UsernameValidators {

  static cannotContainSpace(control: AbstractControl): ValidationErrors | null {
    if ((control.value as string).indexOf(' ') >= 0) {
      console.log('username in validator (cannotContainSpace)', control.value);
      const valError: ValidationErrors = { cannotContainSpace: true };
      return { cannotContainSpace: true };
    }
    return null;
  }
}

这就是我在页面中使用验证器的方式:

ngOnInit() {
  this.registrationForm = new FormGroup({
    username: new FormControl(
      '',
      [Validators.required, UsernameValidators.cannotContainSpace],
      UsernameValidators.shouldBeUnique
    ),
    password: new FormControl(''),


  });
}

在我看来:

<ion-item lines="full">
   <ion-label position="floating">Username</ion-label>
   <ion-input type="text" formControlName="username"></ion-input>
   <div
     *ngIf="username.errors.cannotContainSpace && username.touched"
     class="alert alert-danger"
   >
     Username cannot contain space.
   </div>
   <div
     *ngIf="username.errors.required && username.touched"
     class="alert alert-danger"
   >
     Username is required.
   </div>
   <div
     *ngIf="username.errors.shouldBeUnique && username.touched"
     class="alert alert-danger"
   >
     Username is already taken.
   </div>
   <div *ngIf="username.pending">Verfügbarkeit wird überprüft...</div>
</ion-item>

我究竟做错了什么? 万分感谢!

AbstractControl.errors可能返回 null。因此,您需要对username.errors使用可选链接 (?.)以防止在nullundefined时访问链接属性。

? . 运算符就像. 链接运算符,除了如果引用为空( nullundefined )时不会导致错误,表达式会短路并返回 undefined 值。 当与 function 调用一起使用时,如果给定的 function 不存在,则返回 undefined。

<div
  *ngIf="username.errors?.cannotContainSpace && username.touched"
  class="alert alert-danger"
>
  Username cannot contain space.
</div>
<div
  *ngIf="username.errors?.required && username.touched"
  class="alert alert-danger"
>
  Username is required.
</div>
<div
  *ngIf="username.errors?.shouldBeUnique && username.touched"
  class="alert alert-danger"
>
  Username is already taken.
</div>

StackBlitz 上的示例解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM