异步表单验证角度8后自动调用方法

时间:2019-11-12 09:16:08

标签: angular angular-reactive-forms angular-validation reactive-forms

是否仍然有调用方法像checkValidity()一样自动设置{'invalid':false / true} 在异步表单验证之后(即我有this.uniqueNameValidator .bind(this))异步调用)

已选中https://stackoverflow.com/a/49520534/1225526,但看起来像在提交点击操作后调用提交方法

尝试过Form.valueChanges不能按预期在验证之前调用

this.editForm.valueChanges
            .pipe(takeUntil(this._onDestroy))
            .subscribe(changes => {
                if (changes) {
                    this.onChange(Object.assign({userId: this.userId}, changes));
                }
                this.checkValidity(); <-- This part is not working as expected it is called before validation
            });



checkValidity() {
        if (((this.editForm.controls.userName.pristine && this.editForm.controls.userName.pending) ||
            !this.editForm.controls.userName.invalid)
            && !this.editForm.controls.password.invalid) {
            this.editForm.setErrors({ 'invalid': false });
        } else {
            this.editForm.setErrors({ 'invalid': true });
        }
    }

this.editForm = new FormGroup({
              userDisplayName: new FormControl({ value: '', disabled: true }),
              userName: new FormControl('', [ Validators.required], 
                       this.uniqueNameValidator.bind(this)), <-- async Validation
              password: new FormControl('',[Validators.required,
                       validateUserPassword()])});


uniqueNameValidator(control: AbstractControl) {
        return control.valueChanges.pipe(
            switchMap(() => this.service.checkUsernameAvailability(control.value)),
            take(1),
            map(({data}) => {
                control.markAsTouched();
                this.componentChangeDetector.markForCheck();
                return data.checkUsernameAvailability ? null : {invalid: false};
            }), catchError((error): any => {
                return of(null);
            }));
    }

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

AbstractControl提供了两个Observables valueChangesstatusChanges,也许这些可以帮助您。