TypeError 中的 FormControl 验证器结果无法读取未定义的 属性

FormControl validator result in TypeError cannot read property of undefined

我的用户只能在文本类型的输入中输入特定值。

这里是 app.component.ts:

export class AppComponent implements OnInit {
  myForm: FormGroup;
  allowedValuesArray = ['Foo', 'Boo'];

  ngOnInit() {
    this.myForm = new FormGroup({
      'foo': new FormControl(null, [this.allowedValues])
    });        
  }

  allowedValues(control: FormControl): {[s: string]: boolean} {
    if (!this.allowedValuesArray.indexOf(control.value)) {
      return {'notValidFoo': true};
    }        
    return {'notValidFoo': false};
  }
}

app.component.html:

<form [formGroup]="myForm">
  Foo: <input type="text" formControlName="foo">
  <span *ngIf="!myForm.get('foo').valid">Not valid foo</span>
</form>

在页面加载时抛出此异常:

TypeError: Cannot read property 'allowedValuesArray' of undefined at push../src/app/app.component.ts.AppComponent.allowedValues (app.component.ts:20) at forms.js:1170 at Array.map () at _executeValidators (forms.js:1170) at FormControl.validator (forms.js:1132) at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runValidator (forms.js:2931) at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2907) at new FormControl (forms.js:3267) at AppComponent.push../src/app/app.component.ts.AppComponent.ngOnInit (app.component.ts:15) at checkAndUpdateDirectiveInline (core.js:21097)

它来自这一行以及 this 关键字的工作原理:

if (!this.allowedValuesArray.indexOf(control.value)) {
  return {'nameIsForbidden': true};
} 

你不是自己执行方法(或函数),你只是让Angular执行它并验证字段。由于您允许对 Angular 执行此操作,因此 this 不再引用 AppComponent。你需要做的是 .bind AppComponent 函数,或者我相信用这样的箭头样式函数替换它:

fun = (formControl: FormControl) => null

正如KamLar所说,它来自这一行:

if (!this.allowedValuesArray.indexOf(control.value)) {
  return {'nameIsForbidden': true};
} 

你可以用

处理它
'foo': new FormControl(null, [this.allowedValues.bind(this)])