我有两个日期输入 - “开始日期”和“结束日期” - 我还有两个指令,我用作验证器 - 每个字段允许的最小值和允许的最大值(这样开始日期不会是从结束日期开始)。例如,如果我将开始日期更改为晚于结束日期,验证程序将警告它无效。当我将结束日期从开始日期更改为更晚的日期时 - 由于我没有触发“customMax”验证器,因此此警报不会消失。如何在其中一个字段中的每次更改时立即触发两个验证器?
谢谢,
输入HTML:
<input
type="text" class="form-control"
name="startDate{{d.index}}"
required
[customMax]="d.endDate"
(dateChange)="onDateChange('startDate', d.index, $event)"
[(ngModel)]="d.startDate"
appMyDatePicker>
<input type="text" class="form-control"
required
[customMin]="d.startDate"
name="endDate{{d.index}}"
(dateChange)="onDateChange('endDate', d.index, $event)"
[(ngModel)]="d.endDate"
appMyDatePicker>
customMax指令:
@Directive({
selector: '[appCustomMaxValidator],[customMax][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting:
CustomMaxValidatorDirective, multi: true}]
})
export class CustomMaxValidatorDirective implements Validator {
@Input()
customMax: Date;
constructor() { }
validate(c: FormControl): {[key: string]: any} {
const maxDateConvertInit = moment(this.customMax, 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
console.log('cant be greater than:' + maxDateConvertInit);
const maxDateConvertCompare = moment(c.value, 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
console.log('check date:' + maxDateConvertCompare);
const testScore = (maxDateConvertInit <= maxDateConvertCompare) ? {'customMax': true} : null;
return testScore;
}
}
customMin指令:
@Directive({
selector: '[appCustomMinValidator],[customMin][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting: CustomMinValidatorDirective, multi: true}]
})
export class CustomMinValidatorDirective implements Validator {
@Input()
customMin: Date;
constructor() { }
validate(c: FormControl): {[key: string]: any} {
const minDateConvertInit = moment(this.customMin, 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
const minDateConvertCompare = moment(c.value, 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
const testScore = (minDateConvertInit >= minDateConvertCompare) ? {'customMin': true} : null;
return testScore;
}
}
恕我直言,这应该由您的组件处理。你应该触发markAsTouched:
https://angular.io/api/forms/AbstractControl#markAsTouched
一旦其中一个更改,就在两个FormControl上。这应该强制验证器重新计算。在我的应用程序中,我使用以下服务:
import {Injectable, ChangeDetectorRef} from '@angular/core';
import {FormControl, NgForm} from '@angular/forms';
@Injectable()
export class FormService {
constructor() {}
public handleInvalidControls(form: NgForm, changeDetector: ChangeDetectorRef) {
this.markInvalidControlsAsTouched(form);
changeDetector.detectChanges();
}
private markInvalidControlsAsTouched(form: NgForm) {
for (const key in form.form.controls) {
const control = form.form.controls[key];
if (control instanceof FormControl && control.invalid) {
control.markAsTouched();
}
}
}
}
要从组件访问表单,您需要在模板中使用Angulars ViewChild decorator:
<form #submitForm="ngForm">
在您的组件中:
@Injectable()
export class FormComponent {
@ViewChild('submitForm')
submitForm;
...
}