首页 > 解决方案 > 无法从 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 在类构造函数之后运行,所以无论如何这不应该是问题,但这就是我想尝试的全部。

谢谢。

标签: angulartypescript

解决方案


  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;
      };
    }

推荐阅读