In this post we are going to enable reCAPTCHA in Angular8 application step by step. First of all we need to register site and generate key.
Go to:
Click on Create to register new site:
Add domain in domain section in this example I am going to test in localhost so label it as localhost. Submit the form by accepting terms.
After completing registration below page will appear with site key which we are going to use later in our site.
Clone Repository:
Open the local copy using Visual Studio Code then go to the Terminal to execute command: “npm install”.
After completing installation press “Ctrl+Shift+p” to open command palette, choose and run “gulp: lib-js” task to copy required libraries to lib folder. Get help: https://shashangka.com/2019/11/10/visual-studio-code-gulp-task
Install Google reCAPTCHA
Install through: “npm i ng-recaptcha –save”
After successfully installation add below task to “gulpfile.js”:
gulp.src('./node_modules/ng-recaptcha/**/*.+(js|js.map)')
.pipe(gulp.dest(root_path.package_lib + 'ng-recaptcha'));
Then again run “gulp: lib-js” task.
In “systemjs.config.js” add package to load:
// ng-recaptcha
'ng-recaptcha': 'npm:ng-recaptcha/bundles/ng-recaptcha.umd.js'
Open module.ts to import RecaptchaModule
import {RecaptchaModule, RECAPTCHA_SETTINGS, RecaptchaSettings} from 'ng-recaptcha';
import {RecaptchaFormsModule} from 'ng-recaptcha';
Then in NgModule configuration:
imports: [
CommonModule,
BrowserModule,
HttpModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forRoot(
routes,
{
//enableTracing: false,
useHash: false,
preloadingStrategy: PreloadAllModules
}),
RecaptchaModule,
RecaptchaFormsModule
]
In providers:
providers: [
Title,
PreloadAllModules,
{
provide: LocationStrategy,
useClass: HashLocationStrategy
},
{
provide: RECAPTCHA_SETTINGS,
useValue: {
siteKey: 'YOUR_SITE_KEY',
} as RecaptchaSettings
}
]
After global configuration we are good to go to load the reCAPTCHA. In this example we modified the home page to create and load form.
Loading the reCAPTCHA
Html:
Component:
public reactiveForm: FormGroup;
In ngOnInit() function:
this.reactiveForm = this.formBuilder.group({
exampleInputEmail1: new FormControl('', Validators.required),
exampleInputPassword1: new FormControl('', Validators.required),
recaptchaReactive: new FormControl(null, Validators.required)
});
Go to the Terminal, execute command “npm run start” to start the application. To build execute “npm run build” command.
Output:
As we can see from below image the google reCAPTCHA is enabled in home page.
Hope this post is going to help better understand how to enable and load reCAPTCHA using Angular8, Thanks.
Download/clone full source code from , Thanks.