angular - 无法从 Angular OnInit 方法访问父对象?
问题描述
我正在尝试将自定义验证器附加到 Angular 表单控件。我在 ngOnInit 方法中初始化表单控件。此验证器应检查该字段是否已被输入(很像 Validators.required),但前提是布尔类成员this.shouldCheck
为真。
但是,当我尝试从验证器函数访问该类成员时,它找不到this
. 我知道在 Js 中有一些臭名昭著的范围界定问题this
,但我认为这可以通过 Typescript 解决。不知道如何在验证器中检查该布尔值。
我的组件.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。
我尝试使用简单的空检查:
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;
};
}
推荐阅读
- angular - 如何有条件地阻止用户导航到 mat-tab-group 中的其他选项卡
- c# - 以 C# 形式循环所有面板
- visual-studio - 如何在visual studio 2017中导出应用程序
- python - 除非我使用嵌入,否则 RNN 分类会失败。没有嵌入,所有预测都是同一个类
- excel - 在条件格式中配置3条规则后,颜色在Excel中显示错误
- php - PHP - 如何获取 sql 结果的所有值并使用 group by 存储到数组中
- regex - 当我尝试在 django=1.9 中通过正则表达式将参数从 url 传递到视图时,我得到了这个错误,我不知道为什么
- ios - 使用所需的动画和方向为特定视图设置动画
- javascript - 带有 html 表单文本的字符串插值
- javascript - React 组件的 props 是如何异步更新的?