gpt4 book ai didi

forms - Angular2 - 在验证指令中访问 AbstractControl 实例

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:59 25 4
gpt4 key购买 nike

我必须从验证器指令内部触发验证。

这是我的指令。它按预期工作。但是我希望它在验证器函数更改时触发验证过程。 IE。当它的输入变量 maxDate 改变时。

我该怎么做?

如果我可以在构造函数中访问 AbstractControl 实例,我就可以轻松地做到这一点。但是,我想不出办法。

import { AbstractControl, FormGroup, ValidatorFn, Validator, NG_VALIDATORS, Validators } from '@angular/forms';
import { Directive, Input, OnChanges, SimpleChanges, EventEmitter } from '@angular/core';


function parseDate(date: string):any {
var pattern = /(\d{2})-(\d{2})-(\d{4})/;
if (date) {
var replaced = date.search(pattern) >= 0;
return replaced ? new Date(date.replace(pattern,'$3-$1-$2')) : null;
}

return date;
}


export function maxDateValidator(maxDateObj): ValidatorFn {
return (control:AbstractControl): {[key: string]: any} => {
const val = control.value;

let date = parseDate(val);
let maxDate = parseDate(maxDateObj.max);

if (date && maxDate && date > maxDate) {
return {
maxDateExceeded: true
};
}
return null;
};
}

...

@Directive({
selector: '[maxDate]',
providers: [{provide: NG_VALIDATORS, useExisting: maxDateDirective, multi: true}]
})
export class maxDateDirective implements Validator, OnChanges {
@Input() maxDate: string;

private valFn = Validators.nullValidator;

constructor() { }

ngOnChanges(changes: SimpleChanges): void {
const change = changes['maxDate'];
if (change) {
const val: string = change.currentValue;
this.valFn = maxDateValidator(val);
}
else {
this.valFn = Validators.nullValidator;
}
//This is where I want to trigger the validation again.
}

validate(control): {[key: string]: any} {
return this.valFn(control);
}
}

用法:

  <input type="text" [(ngModel)]="deathDateVal">

<input class="form-control"
type="text"
tabindex="1"
[maxDate]="deathDateVal"
name="will_date"
[textMask]="{pipe: datePipe, mask: dateMask, keepCharPositions: true}"
ngModel
#willDate="ngModel">

最佳答案

这是我刚刚想出的:

@Directive({
selector: '[maxDate]',
providers: [{provide: NG_VALIDATORS, useExisting: maxDateDirective, multi: true}]
})
export class maxDateDirective implements Validator, OnChanges {
@Input() maxDate: string;

private valFn = Validators.nullValidator;
private control:AbstractControl;

constructor() { }

ngOnChanges(changes: SimpleChanges): void {
const change = changes['maxDate'];
if (change) {
const val: string = change.currentValue;
this.valFn = maxDateValidator(val);
}
else {
this.valFn = Validators.nullValidator;
}

if (this.control) {
this.control.updateValueAndValidity(this.control);
}
}

validate(_control:AbstractControl): {[key: string]: any} {
this.control = _control;
return this.valFn(_control);
}
}

它有效。 Validate 在初始化时被调用,所以我只存储它的参数。这真他妈的丑陋,但它确实有效。

关于forms - Angular2 - 在验证指令中访问 AbstractControl 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41880232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com