简体   繁体   English

自定义表单控件上的角度ExpressionChangedAfterItHaHasBeenCheckedError

[英]Angular ExpressionChangedAfterItHasBeenCheckedError on custom form control

My Angular app works fine but after I try to implement ngAfterViewInit on a directive I get the following error: 我的Angular应用程序运行正常,但是尝试在指令上实现ngAfterViewInit之后,出现以下错误:

在此处输入图片说明

Here is the code which I tried to implement: 这是我尝试实现的代码:

  ngAfterViewInit() {
    this.control = this.injector.get(NgControl).control;
    this.setValidator();
  }


  private setValidator() {
    this.control.setValidators(Validators.required);
    this.control.updateValueAndValidity();
  }

The code is based on this blog post (implements reCAPTCHA with Angular). 该代码基于博客文章(使用Angular实现reCAPTCHA)。

I already read a SO answer which described the error but I can't fix it in my particular situation. 我已经阅读了描述错误的SO解答 ,但在我的特定情况下无法解决它。

Question: 题:

Why am I getting this error and what can I do to fix this? 为什么会出现此错误,我该怎么解决?

If you need any additional code or info please comment. 如果您需要任何其他代码或信息,请发表评论。

Keep the function this.setValidator() in settimeout 将函数this.setValidator()保留在settimeout中

 ngAfterViewInit() {
    this.control = this.injector.get(NgControl).control;
    setTimeout (()=> {
        this.setValidator();
    },0);
  }

For more info on this error read this 有关此错误的更多信息,请阅读此内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM