【问题标题】:Validation causing ExpressionChangedAfterItHasBeenCheckedError验证导致 ExpressionChangedAfterItHasBeenCheckedError
【发布时间】:2018-06-07 08:10:37
【问题描述】:

我有以下验证器方法:

static emptyControl(control: FormControl): any {

    if (!control.value || control.value=="") {
      return {
        message: "must not be empty"
      };
    }

    return null;

  }

如果我在表单控件上使用它,则会收到错误:ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'false'. Current value: 'null'. 如果我返回错误而不是 null,错误就会消失。

首先我将输入绑定到一个未初始化的变量,然后在 ngOnInit 中进行异步调用,并将返回的值分配给 subscribe 中的该变量。

验证空/未设置字段的正确方法是什么?

【问题讨论】:

  • 我猜组件在 intalized 时为空,然后添加值并检查 empty ,因此即使在应用角度变化检测之前值也会发生变化,you can make use of required to do this i guess to check empty fields
  • Angular 内置了表单验证器,Required 与非空基本相同。 angular.io/api/forms/RequiredValidator
  • 尝试了内置验证器。导致同样的错误,两次。
  • 这篇文章对你有帮助blog.angularindepth.com/…
  • 它并没有真正帮助,因为这与验证器有关。如果我不验证相同的代码运行没有问题。如您所见,我没有在验证器的组件或视图模型上设置任何内容。所以这更像是一个验证器问题。我怀疑Previous value: 'false'. Current value: 'null' 中的值是一个框架变量,不是我定义的。

标签: angular


【解决方案1】:

您正在混合模板驱动表单和反应式表单。请选择其中之一。有两个绑定 ngModelformControl 有时会出现这种不受欢迎的行为。

相反,将值设置为 表单控件 而不是您的 ngModel,即完全删除 ngModel。如果您想稍后设置一个值,请使用setValue

 this.someFormGroup.get('text').setValue('foo')

还要从模板中删除任何验证,因此从模板中删除 required 并改用 Validators.required,因为您使用的是响应式表单。同样如 cmets 中所述,您不需要自定义验证器,因为 Validators.required 是您想要的。

将您的模板修改为:

<div *ngIf="someFormGroup.hasError('required', 'text') && someFormGroup.controls.text.dirty">
  <label class="errorMessage"> Field is required! </label>
</div>
<form [formGroup]="someFormGroup">
  <input name="text" formControlName="text" />
</form>

TS:

ngOnInit() {
  this.someFormGroup = new FormGroup({
    text: new FormControl('', [Validators.required])
  })
}

您的StackBlitz

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 2020-12-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    相关资源
    最近更新 更多