0

我有一个表单控件:

我尝试了两种不同的方式

    this.passwordForm = new FormGroup({
        oldPassword: new FormControl(),
        newPassword: new FormControl(),
        confirmationPassword: new FormControl()
    })
    this.passwordForm.get("confirmationPassword").setValidators(this.CheckInputMatchValidator("newPassword","confirmationPassword"))

    this.passwordForm = new FormGroup({
        oldPassword: new FormControl(),
        newPassword: new FormControl(),
        confirmationPassword: new FormControl()
    })
    this.passwordForm.setValidators(this.CheckInputMatchValidator("newPassword","confirmationPassword"));

我有这个功能

CheckInputMatchValidator(control1: string, control2: string){
    console.log(this.passwordForm.get(control1).value , this.passwordForm.get(control2).value)
    if(this.passwordForm.get(control1).value != this.passwordForm.get(control2).value){
        console.log("ok")
        this.passwordForm.get(control2).setErrors({notMatching: true});
    } else {
        this.passwordForm.get(control2).setErrors(null);
    }
    return null;
}

模板

<mat-form-field class="full-width">
  <input matInput type="password" placeholder="{{ 'UPDATE_PASSWORD_PANEL.CONFIRM_PASSWORD' | translate }}" formControlName="confirmationPassword" required>
</mat-form-field>
<div *ngIf="passwordForm?.controls.confirmationPassword?.invalid && (passwordForm?.controls.confirmationPassword?.dirty || passwordForm?.controls.confirmationPassword?.touched)" class="alert alert-danger">
    <div *ngIf="passwordForm?.controls.confirmationPassword?.errors?.required">
        {{'INPUT_ERR.REQUIRED' | translate}}
    </div>
    <div *ngIf="passwordForm?.controls.confirmationPassword?.errors?.notMatching">
        {{'INPUT_ERR.INVALID_CONFIRM_PASSWORD' | translate}}
    </div>
</div>

但是 CheckInputMatchValidator 仅在我创建它时调用,而不是每次输入更改时调用。我错过了什么?日志只出现一次。

4

1 回答 1

1

如下更新 CheckInputMatchValidator 函数将起作用。

CheckInputMatchValidator(control1: string, control2: string): ValidatorFn {
     return (control: AbstractControl): { [key: string]: boolean } | null => {
        if(this.passwordForm.get(control1).value != this.passwordForm.get(control2).value){
            this.passwordForm.get(control2).setErrors({notMatching: true});
            return {notMatching: true};
        } else {
            this.passwordForm.get(control2).setErrors(null);
        }
        return null;
     }
}
于 2019-02-13T07:04:15.710 回答