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)