【问题标题】:Angular 7 - call directive on functionAngular 7 - 函数调用指令
【发布时间】:2019-03-13 14:19:15
【问题描述】:

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

}

【问题讨论】:

    标签: angular angular2-directives customvalidator


    【解决方案1】:

    恕我直言,这应该由您的组件处理。你应该触发markAsTouched:

    https://angular.io/api/forms/AbstractControl#markAsTouched

    一旦其中一个发生更改,就在两个 FormControls 上。这应该迫使验证者重新计算。在我的应用中,我使用以下服务:

    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;    
        ...
    }
    

    【讨论】:

    • 您可以添加您的 HTML 模板吗?我无法从 ts 文件访问我的表单标签。
    猜你喜欢
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多