CustomValidator 只调用一次

CustomValidator only called once

我有一个表单控件:

我尝试了两种不同的方式

    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 仅在我创建时调用,而不是每次输入更改时调用。我缺少什么?日志只出现一次。

如下更新 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;
     }
}