自定义Angular 4 Validator取决于动态值

时间:2018-07-21 04:39:53

标签: angular validation angular4-forms

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

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

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

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

我尝试使用@Input validLocationngOnChanges,但是一旦设置了新数据,将如何触发验证,该新数据将在承诺解决后设置。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果我正确理解,您可以将您的诺言或可观察性传递给您的指令,并在其解析时检查其值,例如:

@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(){}
}