组角度验证器在Angular Reactive Form patchValue之后没有启动

时间:2017-08-24 23:12:50

标签: angular angular-reactive-forms angular-validation reactive-forms angular-daterangepicker

我正在使用mydatepicker以下自制助手类:

import {AbstractControl, FormBuilder} from '@angular/forms';

export const dateRangeValidator = (control: AbstractControl): {[key: string]: boolean} => {
	const start = control.get('start');
	const end = control.get('end');
	if (!start || !end) {
		return null;
	}
	if (!start.value || !end.value) {
		return {required: true};
	}
	return start.value.jsdate < end.value.jsdate ? null : {invalid: true};
};

export const createDateRangeGroup = (fb: FormBuilder) => {
	return fb.group({
		start: null,
		end: null
	}, { validator: dateRangeValidator});
};

export const setDateRangeGroupDates = (dates: AbstractControl, start: Date, end: Date) => {
	dates.patchValue({
		start: {
			date: {
				year: start.getFullYear(),
				month: start.getMonth() + 1,
				day: start.getDate()
			}
		},
		end: {
			date: {
				year: end.getFullYear(),
				month: end.getMonth() + 1,
				day: end.getDate()
			}
		}
	});
};

createDateRangeGroup正在组件中使用,如下所示:

this.formGroup = this.fb.group({
  dates: createDateRangeGroup(this.fb)
});
setDateRangeGroupDates(this.formGroup.get('dates'), new Date(2017, 10, 1), new Date(2017, 10, 10));

我可以在屏幕上看到日期设置正确。但是,当我尝试console.log(this.formGroup.get('dates'));时,它会清楚地显示{invalid: true}的错误,即使我只是从下拉列表中重新选择完全相同的日期,该组也会自动生效。

我不做什么?

0 个答案:

没有答案