How to Add Google Recaptcha To Your Website With Angular 2

Posted By : Swati Rahangdale | 28-Apr-2018

These are the Following steps given below :

 

1.Download angular-recaptcha with npm:

npm install --save angular-google-recaptcha

 

2. Add the following to your <head> tag in your main HTML page

To add a reCAPTCHA all you need is to link to Google's reCAPTCHA script, a site key, and a response callback.

The following is the most basic component to implement the reCAPTCHA

 

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
@Component({
template: `<ng2-google-recaptcha
[siteKey]="recaptchaSiteKey"
(onCaptchaComplete)="onCaptchaComplete($event)">
</ng2-google-recaptcha>`,
})
export class BasicComponent {
private recaptchaSiteKey = 'YOUR-RECAPTCHA-SITE-KEY-HERE';
private onCaptchaComplete(response: any) {
console.log('reCAPTCHA response recieved:');
console.log(response.success);
console.log(response.token);
}
}

Once BasicComponent.onCaptchaComplete is called, the response element will contain the following attributes.

Success: True is the request succeeded, False otherwise

Token: The validation token which can be used to validate the users response

Recaptcha: The ng2-google-recpatcha instance this response was generated on

If the users response times out, BasicComponent.onCaptchaComplete will be automatically called with a failed response and a null token, requiring the user to restart the process.

 

3.Import The 'ng2-google-recaptcha' to your angular Module(app.module.ts)

To use ng2-google-recaptcha, you need to import the Ng2GoogleRecaptchaModule into the relevent module in your application. In the sample application, this is done in the entry module - app.module.ts

 

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Ng2GoogleRecaptchaModule } from 'ng2-google-recaptcha';
@NgModule({
imports: [
BrowserModule,
Ng2GoogleRecaptchaModule,
],
bootstrap: [
AppComponent,
],
})
export class AppModule { }

4 Add to your HTML site key:

<div class="g-recaptcha" data-sitekey="6LeEFlYUAAAAAJ0N2AIX3y7byJVQ1q4uc5ep6Gb_"></div>

 

5.Now open your HTML in the browser ,you will be able to see google recapcha as:

  

 

 

 

 

 

About Author

Author Image
Swati Rahangdale

Swati has good konwledge of HTML,CSS, Boostrap.now . She is a UI developer. Her hobbies are watching movie.

Request for Proposal

Name is required

Comment is required

Sending message..