自定义Angular 4验证器取决于动态值



我必须创建一个自定义验证器validLocation

<input [(ngModel)] ="search" (change)="searchLocation" [validLocation] = "location" />

因此,当用户输入值时,searchLocation将获得搜索到的值,并通过Ajax设置location

问题是我如何在验证指令中跟踪location中设置的值

我尝试使用@InputvalidLocationngOnChanges,但如何在设置了新数据后触发验证,该数据将在promise解析后设置。

感谢您的帮助。

如果我理解正确,你可以将你的承诺或可观察性传递给你的指令,并在它解析时检查它的值,比如:

@Directive({ selector: '[validLocation]' })
export class ValidLocation implements OnInit {
isPromiseDone: boolean;
promise: any;
@Input()
set validLocation(passedValue: any) {
if (!passedValue) {
return;
}
const isObservable: boolean = passedValue instanceof Observable;
const isSubscription: boolean = passedValue instanceof Subscription;
const isPromise: boolean = passedValue instanceof Promise;
if (isObservable) {
this.promise = passedValue.toPromise();
} else if (isSubscription) {
this.promise = new Promise((resolve) => {
(passedValue as Subscription).add(resolve);
});
} else if (isPromise) {
this.promise = passedValue;
}
this.checkAndInitPromiseHandler();
}
constructor() {}
initPromiseHandler() {
const promise = this.promise;
this.isPromiseDone = false;
const resolveLoadingState = () => {
this.isPromiseDone = true;
this.doSomething()
};
if (promise.finally) {
promise.finally(resolveLoadingState);
} else {
promise
.then(resolveLoadingState, resolveLoadingState);
}
}
checkAndInitPromiseHandler() {
if (this.promise) {
this.initPromiseHandler();
}
}
ngOnInit() {
this.checkAndInitPromiseHandler();
}
doSomething(){}
}

最新更新