如何在不触发验证的情况下将Value设置为表单控件

问题描述 投票:0回答:1

我正在修改自定义验证器内的控制值,并且由于循环验证的明显问题,我不需要触发验证。

@Directive({
  selector: '[myValidator]',
  standalone: true,
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: MyValidatorDirective,
      multi: true,
    },
  ],
})
export class MyValidatorDirective implements Validator {

  validate(control: AbstractControl): ValidationErrors | null {
    return myValidatorFn(
      this.phoneNumberValidationService,
      this.countryCodeControl,
      this.defaultCountryCode
    )(control);
  }
}


export function myValidatorFn(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (control.value) {
      if (control.value.indexOf("something") > 0) {
        return { myError: { value: true } };
      }
      control.setValue(control.value.replace("other", ""));// Some random value change, here is when the validation is called again
    }
    return null;
  };
}
angular angular-forms angular17
1个回答
0
投票

我结束了更改此代码的

setValue
行(我删除了所有验证器,设置了值,然后再次添加):

  const validatorFn = this.validator;
  if (validatorFn != null) {
    this.clearValidators();
  }
  this.setValue(value, options);
  if (validatorFn != null) {
    this.addValidators(validatorFn);
  }
© www.soinside.com 2019 - 2024. All rights reserved.