3

How to Integrate reCAPTCHA in your Angular 2 Application?

2
  • 1
    Please show us what you have tried before, this is not a "we do that for you" site, we help you fixing errors that occur during your try. Commented Feb 21, 2018 at 9:50
  • I don't need an answer. I have posted the answer myself to share it with others. Commented Feb 21, 2018 at 10:20

3 Answers 3

7

Assuming that you have Site Key and Client Secret given by reCAPTCHA. Put below code in component.

@ViewChild('captchaRef2') captchaRef2: ElementRef;
private _reCaptchaId: number;
private SITE_ID = [YourSiteKey];

ngAfterViewInit() {
    const grecaptcha = (window as any).grecaptcha;
    if (grecaptcha) {
      this._reCaptchaId = grecaptcha.render(this.captchaRef2.nativeElement, {
        'sitekey': this.SITE_ID,
        'callback': (resonse) => this.reCapchaSuccess(resonse),
        'expired-callback': () => this.reCapchaExpired()
      });
    }
}

Below is the Success callback function. If the response data has value then reCAPTCHA verified successfully.

reCapchaSuccess(data:any){
    if(data){
      alert("Congratulation! reCAPTCHA verified.")
      // Some logic goes here
    }
  }

Below function will be called when reCAPTCHA expired.

reCapchaExpired(){
    alert("Oops! reCAPTCHA expired.")
    // Some logic goes here
  }

Put below div in the HTML file.

<div #captchaRef2></div>

Put below JS script in index.html file.

<script src='https://www.google.com/recaptcha/api.js?render=explicit" async defer'></script>
Sign up to request clarification or add additional context in comments.

1 Comment

With Angular 8 @ViewChild asks for 2 parameters. I've provided null as the second one and it worked.
0

By putting above js script, sometimes I face below error: "grecaptcha.render is not a function" so, in case you face this error just use following js script instead of above

<script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>

cheers!

Comments

0

Why overcomplicating that much if ng-recaptcha exists?

  1. yarn add ng-recaptcha or npm i ng-recaptcha --save

  2. In one of your modules (such as app.module.ts, shared.module.ts, etc.)

(like explained here)

import { RecaptchaModule, RECAPTCHA_SETTINGS, RecaptchaSettings } from 'ng-recaptcha';

@NgModule({
  imports: [RecaptchaModule],
  providers: [
    {
      provide: RECAPTCHA_SETTINGS,
      useValue: { siteKey: '<YOUR_KEY>' } as RecaptchaSettings,
    },
  ],
}) export class MyModule { }
  1. Use it in your html as <re-captcha>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.