Angular 4 - validator custom function this is undefined
The context in the foo method when called from within the FormControl is not referencing the FormComponent.
You can do the following to fix this behavior using bind to set the context yourself:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
formInsurance:FormGroup;
private id:FormControl;
constructor(){}
ngOnInit() {
const id = new FormControl('',[
Validators.required,
Validators.minLength(3),
Validators.maxLength(10),
Validators.pattern('^[0-9]+(-[0-9]+)+$|^[0-9]+$'),
this.foo.bind(this)
]);
this.id = id;
this.formInsurance = new FormGroup({
id
})
}
foo(control:FormControl) {
this.boo();
if(control.value){
return {
objToReturn: {
returned: name
}
};
}
return null
}
boo(){
console.log('boo')
}
}
And of course, the other alternative is the arrow function, which auto-binds to the this
context:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, ValidationErrors } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
formInsurance:FormGroup;
private id:FormControl;
constructor() {}
ngOnInit() {
this.id = new FormControl('',[
Validators.required,
Validators.minLength(3),
Validators.maxLength(10),
Validators.pattern('^[0-9]+(-[0-9]+)+$|^[0-9]+$'),
this.foo
]);
this.formInsurance = new FormGroup({
id:this.id
})
}
foo = (control: FormControl): ValidationErrors => {
this.boo();
if (control.value) {
return {
objToReturn: {
returned: name
}
};
}
return null
}
boo() {
console.log('boo')
}
}