[英]Can't access parent object from Angular OnInit method?
我正在嘗試將自定義驗證器附加到Angular Form Control。 我正在ngOnInit方法中初始化窗體控件。 該驗證器應檢查字段是否已輸入(類似於Validators.required),但僅當布爾類成員this.shouldCheck
為true時。
但是,當我嘗試從驗證器函數訪問該類成員時,它找不到this
的實例。 我知道有一些臭名昭著的范圍的問題this
在JS,但我認為這是與打字稿解決。 不知道如何在驗證器中檢查該布爾值。
我的component.ts:
// this shouldCheck's value is bound to a checkbox on the form
private shouldCheck: boolean = false;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.employeeCreateForm = this.formBuilder.group({
firstName: [null, [
this.myRequiredValidator,
Validators.maxLength(30),
Validators.pattern('[^<|]+$')]],
lastName: [null, [
this.myRequiredValidator,
Validators.maxLength(40),
Validators.pattern('[^<|]+$')]]
}
我的自定義驗證器:
myRequiredValidator(control: AbstractControl): ValidationErrors | null {
// if shouldCheck, perform a basic "required field" validation
if (this.shouldCheck) {
return !!control.value ? null : {required: true};
}
// else, don't apply validation error
return null;
}
不管我在哪里初始化shouldCheck
,驗證器函數都無法解決this
,因此甚至無法實例化FormGroup。
我嘗試使用簡單的null檢查:
if (this && this.shouldCheck) {
// do validation
}
...這可以構造FormGroup,但即使在初始化窗體之后,它似乎也永遠無法解析this
。 我知道ngOnInit在類構造函數之后運行,因此無論如何都不應該是問題,但這就是我想嘗試的全部。
謝謝。
nameRequiredValidator = (control: AbstractControl): ValidationErrors | null => {
// if shouldCheck, perform a basic "required field" validation
if (this.shouldCheck) {
return !!control.value ? null : {required: true};
}
// else, don't apply validation error
return null;
}
要么
ngOnInit() {
this.employeeCreateForm = this.formBuilder.group({
firstName: [null, [
this.myRequiredValidator(),
Validators.maxLength(30),
Validators.pattern('[^<|]+$')]],
lastName: [null, [
this.myRequiredValidator(),
Validators.maxLength(40),
Validators.pattern('[^<|]+$')]]
}
myRequiredValidator(): (AbstractControl) => ValidationErrors | null {
return (control: AbstractControl): ValidationErrors | null => {
// if shouldCheck, perform a basic "required field" validation
if (this.shouldCheck) {
return !!control.value ? null : {required: true};
}
// else, don't apply validation error
return null;
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.