问题
My users are allowed to enter only specific values to an input of text type.
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};
}
}
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: 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)
回答1:
Like KamLar said, it comes from this line:
if (!this.allowedValuesArray.indexOf(control.value)) {
return {'nameIsForbidden': true};
}
you can handle it with
'foo': new FormControl(null, [this.allowedValues.bind(this)])
回答2:
It comes from this line and how this
keyword works:
if (!this.allowedValuesArray.indexOf(control.value)) {
return {'nameIsForbidden': true};
}
You are not executing method (or function) by yourself, you just let Angular execute it and validate field. Since you are letting to do it to Angular, the this
is no longer referencing to AppComponent
. What you have to do is .bind
AppComponent
to function, or I believe replace it with arrow style functions like this:
fun = (formControl: FormControl) => null
来源:https://stackoverflow.com/questions/60816608/formcontrol-validator-result-in-typeerror-cannot-read-property-of-undefined