Willem van der Veen
Willem van der Veen

Reputation: 36650

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:

enter image description here

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).

I already read a SO answer which described the error but I can't fix it in my particular situation.

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.

Upvotes: 1

Views: 300

Answers (1)

Nandita Sharma
Nandita Sharma

Reputation: 13417

Keep the function this.setValidator() in settimeout

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

For more info on this error read this

Upvotes: 2

Related Questions