How to Integrate reCAPTCHA in your Angular 2 Application?
-
1Please show us what you have tried before, this is not a "we do that for you" site, we help you fixing errors that occur during your try.Marvin Fischer– Marvin Fischer2018-02-21 09:50:57 +00:00Commented Feb 21, 2018 at 9:50
-
I don't need an answer. I have posted the answer myself to share it with others.ruchit– ruchit2018-02-21 10:20:19 +00:00Commented Feb 21, 2018 at 10:20
Add a comment
|
3 Answers
Assuming that you have Site Key and Client Secret given by reCAPTCHA. Put below code in component.
@ViewChild('captchaRef2') captchaRef2: ElementRef;
private _reCaptchaId: number;
private SITE_ID = [YourSiteKey];
ngAfterViewInit() {
const grecaptcha = (window as any).grecaptcha;
if (grecaptcha) {
this._reCaptchaId = grecaptcha.render(this.captchaRef2.nativeElement, {
'sitekey': this.SITE_ID,
'callback': (resonse) => this.reCapchaSuccess(resonse),
'expired-callback': () => this.reCapchaExpired()
});
}
}
Below is the Success callback function. If the response data has value then reCAPTCHA verified successfully.
reCapchaSuccess(data:any){
if(data){
alert("Congratulation! reCAPTCHA verified.")
// Some logic goes here
}
}
Below function will be called when reCAPTCHA expired.
reCapchaExpired(){
alert("Oops! reCAPTCHA expired.")
// Some logic goes here
}
Put below div in the HTML file.
<div #captchaRef2></div>
Put below JS script in index.html file.
<script src='https://www.google.com/recaptcha/api.js?render=explicit" async defer'></script>
1 Comment
senyor
With Angular 8 @ViewChild asks for 2 parameters. I've provided null as the second one and it worked.
Why overcomplicating that much if ng-recaptcha exists?
yarn add ng-recaptchaornpm i ng-recaptcha --saveIn one of your modules (such as
app.module.ts,shared.module.ts, etc.)
(like explained here)
import { RecaptchaModule, RECAPTCHA_SETTINGS, RecaptchaSettings } from 'ng-recaptcha';
@NgModule({
imports: [RecaptchaModule],
providers: [
{
provide: RECAPTCHA_SETTINGS,
useValue: { siteKey: '<YOUR_KEY>' } as RecaptchaSettings,
},
],
}) export class MyModule { }
- Use it in your
htmlas<re-captcha>