I was stuck quite long with errors while implementing a ReCaptcha with Angular. I finally was able to fix this annoying console error.
These were the errors after implementing angular-recaptcha3
(had similar with ngx-recaptcha)
:
NG0100: ExpressionChangedAfterItHasBeenCheckedError
and
unhandled promise rejection: timeout ; zone: <root> ; task: promise.then ; value: timeout zone.js
The solution is the implementation of ChangeDetectorRef. Check out the code below in the ngOnInit method:
import {Component, OnInit } from '@angular/core';
import {AbstractControl, Form, FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {ChangeDetectorRef} from '@angular/core';
@Component({
selector: 'app-register',
templateUrl: 'register.page.html',
})
export class RegisterPage implements OnInit {
registerForm: FormGroup;
public token!: string|null;
constructor(
private readonly fb: FormBuilder,
private ref: ChangeDetectorRef
) {
this.registerForm = this.fb.group(
{
email: ['', [Validators.required, Validators.pattern(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)]],
captcha: ['', Validators.required]
}
);
}
ngOnInit() {
this.ref.detectChanges();
}
onCaptchaExpired(response: any) {
this.token = null;
this.registerForm.controls['captcha'].patchValue(null);
}
onCaptchaResponse(response: string|null) {
this.token = response;
if (response !== null) {
this.registerForm.controls['captcha'].patchValue(response);
}
}
submitForm() {
}
}
}