【发布时间】:2020-04-03 01:31:04
【问题描述】:
我正在尝试根据服务调用结果动态验证自定义文本输入。如果它的 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>
【问题讨论】:
-
问题不是没有收到新的值。如果您使用 setter 或 ngOnCHanges,您可以轻松地检查它。问题是你希望 validate 方法被再次调用,即使表单控件的值没有改变。
标签: angular typescript angular-directive