[英]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.