Adding the Google reCAPTCHA v2 to an Angular application
Introduction
Angular is a development platform for building WEB, mobile and desktop applications using HTML, CSS and TypeScript (JavaScript). Currently, Angular is at version 15 and Google is the main maintainer of the project.
ng-recaptcha is a simple and configurable reCAPTCHA v2 and v3 component library.
Prerequisites
Before you start, you need to install and configure the tools:
Getting started
Create and configure the account on the Google reCAPTCHA
1. Let’s create the account. Access the site https://www.google.com/recaptcha/ and click on the button v3 Admin Console.
2. Fill in the field Email or phone and click on the button Next to login with your Google account and if you don’t have an account, just create a new account.
3. Fill in the field Label, click on the option reCAPTCHA v2, Fill in the field Domains, click on the checkbox Accept the reCAPTCHA Terms of Service and click on the button Submit.
4. Click on the button COPY SITE KEY to copy the key, in my case, the key 6LfKNi0cAAAAACeYwFRY9_d_qjGhpiwYUo5gNW5-
was copied because this key will be configured in the Angular application.
5. Ready! The keys have been generated.
Create the Angular application
1. Let’s create the application with the Angular base structure using the @angular/cli
with the route file and the SCSS style format.
2. Install and configure the Bootstrap CSS framework. Do steps 2 and 3 of the post Adding the Bootstrap CSS framework to an Angular application.
3. Configure the siteKey
variable with the Google reCAPTCHA key in the src/environments/environment.ts
and src/environments/environment.prod.ts
files as below.
4. Install the ng-recaptcha
library.
5. Import the FormsModule
, RecaptchaFormsModule
, RecaptchaModule
modules. Configure the Google reCAPTCHA key. Change the app.module.ts
file and add the lines as below.
6. Remove the contents of the AppComponent
class from the src/app/app.component.ts
file. Import the NgForm
component and create the send
method as below.
7. Remove the contents of the src/app/app.component.html
file. Add the re-captcha
component as below.
8. Add the style in the src/app/app.component.scss
file as below.
9. Run the application with the command below.
10. Ready! Access the URL http://localhost:4200/
and check if the application is working. See the application working on GitHub Pages and Stackblitz.
The application repository is available at https://github.com/rodrigokamada/angular-recaptcha-v2.
This tutorial was posted on my blog in portuguese.