TypeError的FormControl验证器结果无法读取未定义的属性 [英] FormControl validator result in TypeError cannot read property of undefined
问题描述
只允许我的用户为文本类型输入输入特定的值.
My users are allowed to enter only specific values to an input of text type.
这是app.component.ts:
Here is the 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:
The app.component.html:
<form [formGroup]="myForm">
Foo: <input type="text" formControlName="foo">
<span *ngIf="!myForm.get('foo').valid">Not valid foo</span>
</form>
在页面加载时会引发此异常:
On page load it throw this exception:
TypeError:无法读取未定义的属性'allowedValuesArray' 在push ../src/app/app.component.ts.AppComponent.allowedValues(app.component.ts:20) 在forms.js:1170 在Array.map() 在_executeValidators(forms.js:1170) 在FormControl.validator(forms.js:1132) 在FormControl.push ../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runValidator (forms.js:2931) 在FormControl.push ../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2907) 在新的FormControl(forms.js:3267) 在AppComponent.push ../src/app/app.component.ts.AppComponent.ngOnInit (app.component.ts:15) 在checkAndUpdateDirectiveInline(core.js:21097)
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)
推荐答案
像KamLar所说,它来自以下行:
Like KamLar said, it comes from this line:
if (!this.allowedValuesArray.indexOf(control.value)) {
return {'nameIsForbidden': true};
}
您可以使用
'foo': new FormControl(null, [this.allowedValues.bind(this)])
这篇关于TypeError的FormControl验证器结果无法读取未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!