我正在尝试根据服务调用结果动态地验证自定义文本输入。如果为true,则可以使用jumpyId,否则显示错误。我现在的问题是,当我从fromevent更新this.isAvailable时,它没有反映自定义指令中的值。我期望如果api调用返回true->则指令应接收true,否则返回false。
AvailableDirective.ts
import { Directive, forwardRef, Input } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
@Directive({
selector: 'custom-text-input[vendorAvailable][formControlName],custom-text-input[vendorAvailable][formControl],custom-text-input[vendorAvailable][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useExisting: AvailabilityDirective, multi: true }
]
})
export class AvailabilityDirective implements Validator {
@Input('available') available: boolean;
validate(c: AbstractControl): { [key: string]: any } {
console.log("valid", this.available);
if (!this.available) {
return {
available: false
};
}
return null;
}
}
EventObservable:
fromEvent(this.custom.nativeElement, 'keyup').pipe(
map((event: any) => {
return event.target.value;
})
, debounceTime(1000)
, distinctUntilChanged()
).subscribe((text: string) => {
this.myService.isAvailable(text).subscribe((res) => {
console.log(res);
if (res) {
this.isAvailable = true;
} else {
this.isAvailable = false;
}
}, (err) => {
console.log(err);
});
});
模板:
<custom-text-input *ngIf="drawer"
label="JumpyId"
[(ngModel)]="jumpyId"
id="jumpyId"
name="jumpyId"
required
[available]="isAvailable"
#custom>
</custom-text-input>
添加一个onChanges来监视可用的更改
onChange: () => void;
registerOnValidatorChange(fn: () => void): void {
this.onChange = fn;
}
ngOnChanges(changes: SimpleChanges): void {
if ('available' in changes) {
if (this.onChange) {
this.onChange();
}
}
}
如果我的验证指令依赖于另一个输入,则使用此验证器库
[看起来,您可以使用onChange
来完成这项工作,但是如果您尝试在ngOnChanges
中记录某些内容,您将看到被调用多少次的可怕场景。
我更喜欢使用简单的setter
函数,每次available
变量获得新值时都会调用该函数,例如:
// here to save available value
_available: boolean;
@Input('available')
set available(value: boolean) {
// update _available value
this._value = value;
// do something on available value get changed
}
validate(c: AbstractControl): { [key: string]: any } {
console.log("valid", this._available);
if (!this._available) {
return {
available: false
};
}
return null;
}