简体   繁体   English

无法从Angular OnInit方法访问父对象?

[英]Can't access parent object from Angular OnInit method?

I am attempting to attach a custom validator to an Angular Form Control. 我正在尝试将自定义验证器附加到Angular Form Control。 I am initializing the Form Controls in the ngOnInit method. 我正在ngOnInit方法中初始化窗体控件。 This validator should check that the field has been given an input (much like Validators.required), but only if a boolean class member this.shouldCheck is true. 该验证器应检查字段是否已输入(类似于Validators.required),但仅当布尔类成员this.shouldCheck为true时。

However, when I attempt to access that class member from the validator function, it cannot find the instance of this . 但是,当我尝试从验证器函数访问该类成员时,它找不到this的实例。 I know there are some notorious scoping issues with this in Js, but I thought that was solved with Typescript. 我知道有一些臭名昭著的范围的问题this在JS,但我认为这是与打字稿解决。 Not sure how I can check that boolean in the validator. 不知道如何在验证器中检查该布尔值。

My component.ts: 我的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('[^<|]+$')]]
        }

My custom validator: 我的自定义验证器:

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

No matter where I initialize shouldCheck , the validator function can't resolve this and thus cannot even instantiate the FormGroup. 不管我在哪里初始化shouldCheck ,验证器函数都无法解决this ,因此甚至无法实例化FormGroup。

I tried using a simple null check: 我尝试使用简单的null检查:

if (this && this.shouldCheck) {
    // do validation
}

...which allows the FormGroup to be constructed but it never seems to be able to resolve the this , even after the form has been initialized. ...这可以构造FormGroup,但即使在初始化窗体之后,它似乎也永远无法解析this I know ngOnInit runs after the class constructor so that shouldn't have been the issue anyway, but that's all I could think to try. 我知道ngOnInit在类构造函数之后运行,因此无论如何都不应该是问题,但这就是我想尝试的全部。

Thanks. 谢谢。

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

Or 要么

  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM