I need to create a form that will contain 2 dates, dateFrom and dateTo. The condition for validation is that dateFrom cannot be after dateTo and dateTo cannot be before dateFrom.
So I created a form group with two form controls and a validator in common that will check this condition.
export class DateRangeSelector { dateForm: FormGroup = new FormGroup({ dateFrom: new FormControl({ year: 2017, month: 10 },[this.dateValidator.bind(this)]), dateTo: new FormControl({ year: 2020, month: 11 }, [this.dateValidator.bind(this)]) }); dateValidator(control: FormControl): { [s: string]: boolean } { const valueDateFrom = this.dateForm.get('dateForm').value; const valueDateTo = this.dateForm.get('dateTo').value; if (valueDateFrom && valueDateTo) { //please ignore the fact that value is {year: x, month: y}, I need to parse const dateFrom = moment(valueDateFrom); const dateTo = moment(valueDateTo); if (dateFrom.isAfter(dateTo)) { return { invalidDate: true }; } } return null; } } My problem is that this.dateForm is not defined (not in the context) when validators try to validate. And I don't understand because I binded the method in the validators declaration.