Why is currentdate
in this.currentdate.getTime()
coming back as undefined?
newlisting = this.formBuilder.group({
availabledate: new FormGroup({
xyz: new FormControl()
},[this.mainservice.getcurrenttime.bind(this)])
})
@Injectable({providedIn: 'root'})
export class MainService {
constructor(){}
currentdate: Date = new Date();
getcurrenttime(control: FormGroup){
console.log(this.currentdate.getTime()) <~~ Generates Error!!!
if(condition){
return {date: true};
}
return null;
}
}
When you do something like this.mainservice.getcurrenttime.bind(this)
, it creates a bound function.
Due to the above created bound function, in your case within getcurrenttime()
method this
would be referred to as YourComponent
instance.
Since the component doesn't have any property named currentdate
declared, this.currentdate
will result in undefined
and trying to read getTime()
on it will result in an error.
mainservice
instancethis.mainservice.getcurrenttime.bind(this.mainservice)
getcurrenttime
as below, so that you don't lose the this
context. (I would recommend this approach)// Within MainService
getcurrenttime(): ValidatorFn {
return (control: AbstractControl) => {
console.log(this.currentdate.getTime());
// Your logic
return null;
}
}
// Within YourComponent
this.mainservice.getcurrenttime()
getcurrenttime
as an arrow function and then you don't need to use bind
.// Within MainService
getcurrenttime = (control: AbstractControl) => {
console.log(this.currentdate.getTime());
// Your logic
return null;
}
// Within YourComponent
this.mainservice.getcurrenttime // No need to use .bind(...)