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.
- @NgModule({
- imports: [
- ReCaptchaModule
- ]
- })
Step 4
Use recatcha template in app.component.html.
- <re-captcha (captchaResponse)="handleCorrectCaptcha($event)" site_key="enter site key"></re-captcha>
- <button (click)="checkCaptcha()">Check Captcha</button>
site_key is the Google reCaptcha public key.
Step 5
Handle the captcha response in app.component.ts.
- import { ReCaptchaComponent } from 'angular2-recaptcha';
- invalidCaptcha: boolean;
- @ViewChild(ReCaptchaComponent) captcha: ReCaptchaComponent;
- handleCorrectCaptcha(data) {
- if (data === '') {
- this.invalidCaptcha = true;
- } else {
- this.invalidCaptcha = false;
- }
- }
- checkCaptcha() {
- const token = this.captcha.getResponse().toString();
- if (token === '') {
- alert('You cant leave Captcha Code empty');
- } else {
- alert('Captcha completed');
- }
- }
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.