![](/img/trans.png)
[英]Angular. Error Cannot read properties of null (reading 'addFormGroup')
[英]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
使用可選鏈接 (?.)以防止在null
或undefined
時訪問鏈接屬性。
的
?
. 運算符就像.
鏈接運算符,除了如果引用為空(null
或undefined
)時不會導致錯誤,表達式會短路並返回 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.