1

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.

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155

1 Answers1

2

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

Nandita Sharma
  • 13,287
  • 2
  • 22
  • 35
  • Do read the blog link I posted. It helps to avoid any such scenarios further – Nandita Sharma May 23 '18 at 17:27
  • There another way mentioned in the blog to fix it, but I wont recommend it as it runs another detection change cycle after angular's one update cycle ends. That means running extra detection change cycles. – Nandita Sharma May 23 '18 at 17:37