Angular - 自定义验证器不使用组件变量的最新值

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

我有以下在

ngOnInit
中创建的表单组:

  private setScreeningStatusForm(screeningStatusData: ClientScreeningStatusModel | undefined): void {
    this.screeningStatusForm = new FormGroup({
      field_screening_status_select: new FormControl(screeningStatusData?.status, [Validators.required, this.screeningStatusValidator().bind(this)]),
      field_screening_status_comment: new FormControl(screeningStatusData?.userComment)
    });
  }

我有以下验证器,可确保用户无法保存相同的选项(其中

this.screeningStatus
是当前保存的选项,并在保存时更新):

  private screeningStatusValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      return this.screeningStatus?.status === control.value ? { 'invalidStatusSelection': true } : null;
    };
  }

我遇到了一个问题,在验证时,验证器使用

this.screeningStatus
的原始值而不是最新值。正如您在代码中看到的,我尝试将
this
绑定到验证器以获取最新值,但没有骰子。

每次

this.screeningStatus
更改时,我是否必须重新创建表单组或删除/重新添加验证器?我有一个可行的解决方案,我在
set
this.screeningStatus
中执行此操作:

  public set screeningStatus(value: ClientScreeningStatusModel | undefined) {
    this._screeningStatus = value;
    this.setScreeningStatusForm(value);
  }

这不需要绑定就可以工作,但是它很笨重,我希望绑定能够工作。我做错了什么?

angular validation angular-reactive-forms
1个回答
0
投票

嗯,我认为你混淆了一些事情。

从我在这里看到的,您正在尝试验证您正在设置的数据,这是相当多余的。

我认为你想做的是:

在 ngOnInit 函数中创建表单,无需使用筛选状态验证器,这是不必要的

ngOnInit(): void {
  this.screeningStatusForm = new FormGroup({
      field_screening_status_select: new FormControl(screeningStatusData?.status, [Validators.required]),
      field_screening_status_comment: new FormControl(screeningStatusData?.userComment)
    });
}

然后,您应该修改您的设置器以将值设置为表单

public set screeningStatus(value: ClientScreeningStatusModel | undefined) {
   this.screeningStatusForm.controls.field_screening_status_select.setValue(value.status);
   this.screeningStatusForm.controls.field_screening_status_comment.setValue(value.userComment;
}
© www.soinside.com 2019 - 2024. All rights reserved.