Angular 7-函数

时间:2019-03-13 14:19:16

标签: angular angular2-directives customvalidator

我输入了两个日期-“开始日期”和“结束日期”- 我还使用两个指令作为验证器-每个字段的允许最小值和允许最大值(以便开始日期不会晚于结束日期)。 例如,如果我将开始日期更改为晚于结束日期,则验证器将警告它无效。 当我将结束日期更改为从开始日期开始的较晚日期时,此警报不会消失,因为我还没有触发“ 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;
  }

}

1 个答案:

答案 0 :(得分:0)

恕我直言,这应该由您的组件处理。您应该触发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;    
    ...
}