Learn About Angular ReCaptcha

Getting started with Angular2 re-captcha using Angular.

In this blog, we will learn how to use Angular2 Re-Captcha in Angular programming.
 
Step 1
 
First, we need to create an Angular project using Angular CLI.
 
ng new demo --skip-tests --spec false
 
--skip-tests command is for removing the test projects
--spec false command is for skipping the test file generation
 
 
Step 2
 
Add angular2-recaptcha package to the project.
 
npm install angular2-recaptcha
 
Step 3
 
Import ReCaptchaModule in app.module.ts.
  1. @NgModule({  
  2.    imports: [  
  3.        ReCaptchaModule  
  4.    ]  
  5. })  
Step 4
 
Use recatcha template in app.component.html.
  1. <re-captcha (captchaResponse)="handleCorrectCaptcha($event)" site_key="enter site key"></re-captcha>  
  2. <button (click)="checkCaptcha()">Check Captcha</button>  
site_key is the Google reCaptcha public key.
 
Step 5
 
Handle the captcha response in app.component.ts.
  1. import { ReCaptchaComponent } from 'angular2-recaptcha';

  2. invalidCaptcha: boolean;  
  3. @ViewChild(ReCaptchaComponent) captcha: ReCaptchaComponent;  
  4. handleCorrectCaptcha(data) {  
  5.   if (data === '') {  
  6.     this.invalidCaptcha = true;  
  7.   } else {  
  8.     this.invalidCaptcha = false;  
  9.   }  
  10. }  
  11. checkCaptcha() {  
  12.   const token = this.captcha.getResponse().toString();  
  13.   if (token === '') {  
  14.    alert('You cant leave Captcha Code empty');  
  15.   } else {  
  16.    alert('Captcha completed');  
  17.   }  
  18. }  
Step 6
 
Run your application.
 
ng serve -o
 
 
Now, click on the "check captcha" option. It shows the validation.
 
 
After success.
 
Conclusion
 
Thanks a lot for reading. I hope you liked this article. Please share your suggestions and feedback.