Implementing CAPTCHA V2 on Angular encounters an Error: It requires the essential parameters, specifically the sitekey

Encountering an issue adding Recaptcha V2 to a simple Angular Page, my knowledge in Angular is limited. The HTML file and component.ts file are referenced below.

Attempting to send this form along with the token to a Laravel API for validation, and return a Success or Error message in the Angular page.

Getting an error in the console related to the recaptcha ngx-recaptcha2 tag. Tried multiple formats without success, so went with a method seen on the Internet.

Unhandled Promise rejection: Missing required parameters: sitekey; Zone:; Task:
Promise.then; Value: Error: Missing required parameters: sitekey

<form #myform="ngForm" (ngSubmit)="onSubmit(myform)">                                
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Enter Your Name" id="inputName" name="name" [(ngModel)]="name" />
    </div>
    <div class="form-group">
       <input type="email" class="form-control" placeholder="Enter your email" id="inputEmail" name="email" [(ngModel)]="email" />
     </div>
     <div class="form-group">
        <input type="tel" class="form-control" placeholder="Enter Your Phone No" id="inputPhone" oninput="process(this)" maxlength ="12" minlength ="10" name="phone" [(ngModel)]="phone" />
      </div>
      <div class="form-group">
          <input type="text" class="form-control" placeholder="Enter Your City Name" id="inputCity" name="city" [(ngModel)]="city"/>
      </div>
      <div class="form-group ml-4">
         <ngx-recaptcha2 #captchaElem name="siteKey" [(ngModel)]="siteKey">
         </ngx-recaptcha2>
       </div>                                  
       <div class="form-group">
       <img src="assets/img/banner-image/payment-icon.png" alt="image">
       </div>
       <button type="submit" class="btn btn-gradient">Download</button>
  </form> 

component.ts file

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { ReCaptchaV3Service } from 'ngx-captcha';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {  
  
  protected aFormGroup: FormGroup;
  
  siteKey: string;
 
  constructor(private formBuilder: FormBuilder,private http: HttpClient,private reCaptchaV3Service: ReCaptchaV3Service) { 
    this.siteKey = "6LcwHUEaAAAAAIiWj1j8EYHDXuHl1_HZatabWR9U";
  }
  
 
  ngOnInit() {

    this.aFormGroup = this.formBuilder.group({
      recaptcha: ['', Validators.required]
    });    

  } 

Answer №1

If you encounter this particular Error, fear not! After extensive research, a solution has been found to resolve this issue.

Simply add a few lines of code,
Make sure to import ElementRef and ViewChild. Next, include two functions: renderReCaptch() and addRecaptchaScript().
Then call 'this.addRecaptchaScript()' within the ngOnInit function. Also, add a new empty div in the HTML with an ID of "recaptcha".

Be sure to compare the relevant files to ensure the fix works smoothly. Best of luck! :)

.html file and component.ts file

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { ReCaptchaV3Service } from 'ngx-captcha';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})<br>
export class HomeComponent implements OnInit {  

  @ViewChild('recaptcha', {static: true }) recaptchaElement: ElementRef;
  
  protected aFormGroup: FormGroup;
  
  siteKey: string;
 
  
  constructor(private formBuilder: FormBuilder,private http: HttpClient,private reCaptchaV3Service: ReCaptchaV3Service) 
  {  
   this.siteKey = "SiteKey";
  }
  
 
  ngOnInit() {
    this.addRecaptchaScript();      

  }

  renderReCaptch() {
    window['grecaptcha'].render(this.recaptchaElement.nativeElement, {
      'sitekey' : 'SiteKey',
      'callback': (response) => {
          console.log(response);
      }
    });
  }

  addRecaptchaScript() {
 
    window['grecaptchaCallback'] = () => {
      this.renderReCaptch();
    }
 
    (function(d, s, id, obj){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) { obj.renderReCaptch(); return;}
      js = d.createElement(s); js.id = id;
      js.src = "https://www.google.com/recaptcha/api.js?onload=grecaptchaCallback&amp;render=explicit";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'recaptcha-jssdk', this));
 
  }
}

html file
<div class="form-group ml-4">
  <div #recaptcha ></div>
</div>  

Answer №2

File: Component.ts

siteKey: any = "";
ngOnInit(): void {
this.aFormGroup = this.formBuilder.group({
  recaptcha: ['', Validators.required]
});    
this.siteKey = "your site key";
}

Code in HTML

<ngx-recaptcha2 #captchaElem
          [siteKey]="siteKey"
          formControlName="recaptcha">
        </ngx-recaptcha2>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Improper Alignment of Bootstrap 4 Navbar Link: Troubleshooting Required

Take a look at the image for the issue: https://i.stack.imgur.com/u9aCy.png As shown in the image, the NavBar links are stacked instead of being displayed in one row. This is the HTML code I have used: <!doctype html> <html> <head> ...

Using `it` with accessing class members

When testing whether a specific object/class is correctly wired up, I often utilize it.each to prevent writing repetitive tests. The issue arises when the type of the object doesn't have an index signature, requiring me to cast it to any for it to fun ...

Looking for guidance on locating Typescript type definitions?

As a newcomer to Typescript, I have recently delved into using it with React. While I have grasped the fundamentals of TS, I find myself perplexed when it comes to discovering or deriving complex types. For example, in React, when dealing with an input el ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

Encountering an "Invalid parameter: redirect_uri" error in Keycloak while manually refreshing the page

This is an Angular 17 single-page application utilizing the latest version of keycloak-angular (15.2.1 at the time of writing). I'm facing a perplexing issue where after successfully authenticating and logging out, if I reload the page, it breaks enti ...

Encountering "environment.prod.ts path does not exist in file replacements" error while Dockerizing Angular build

I am encountering an issue with a Dockerfile that throws an error during the build process. I attempted to install the angular/cli globally and run ng build --prod using a separate RUN command, but the same error persists. Dockerfile FROM node:12.17.0-al ...

Is there a way for me to trigger an error within my Django form?

Currently, I have set up a PHP script on a server that responds with {"available":true} or {"available":false} based on the availability of an email address. The code used for this script is as follows: <?php $servername = "localhost"; $username = "ro ...

Unable to simulate axios instance in a Typescript environment

After reading through this particular article, I decided to attempt writing a unit test while simulating Axios (with Typescript). Incorporating an Axios instance to define the baseUrl. // src/infrastructure/axios-firebase.ts import axios from 'axios ...

I would like to modify the text color of a disabled input field

I need to adjust the font color of V1, which is a disabled input field. I want to make it darker specifically for Chrome. Any suggestions on how I can achieve this? https://i.sstatic.net/kioAZ.png Here's my HTML code: <mat-form-field appearance= ...

mat-stepper each individual stage within the component

My goal is to incorporate a mat-stepper where each step is contained in a separate component. However, I am encountering an issue with preventing the next button from being clicked if the step is not completed: parent.html: <mat-horizontal-stepper> ...

automatic slideshow plugin for Ionic 4

I've been working on implementing an auto slide feature for Ionic 4, but I'm having trouble getting it to work. Here's the code snippet: page.ts ========= @ViewChild(IonSlides) slider: IonSlides; options: { autoplay: true } HTML ...

What is the method for reaching a static member of a class within a decorator for a method of the same class?

Upon the release of TypeScript 5.0, the new decorator APIs have been introduced and I am eager to utilize them for automatically providing parameters to a method from a static property within the same class. The decorator parameters and factory are defined ...

What are the steps to reduce the node version?

How can I downgrade my npm version from 16.13.1 to 12.0.1? Any guidance would be greatly appreciated! Thank you in advance. ...

What is the best way to implement NgClass on a single iteration within NgFor while utilizing parent/child components?

My goal is to toggle the visibility of tiered buttons when a parent button is clicked. I am using ngFor to generate three buttons on tier 1, but I'm struggling to select only the desired tier when clicked instead of affecting all of them. I've m ...

What is the reason for not requiring checks with Union Types when utilizing a variable, yet necessitating them within a function?

Currently working on some Typescript challenges and encountered a scenario involving a union type. In this example, the function getIstanbulPostalCode is declared to return either a string or a number: function getIstanbulPostalCode(): string | number { ...

Guidelines for automatically exporting (and downloading) a Highcharts chart created in Angular

I've been working on an Angular project where I successfully created a chart using the Highcharts library and the Angular-Highcharts package. The chart looks great, but now I'm facing an issue with automatically exporting it using the Highcharts ...

Utilizing Mongoose Typescript 2 Schema with fields referencing one another in different schemas

I'm currently facing an issue as I attempt to define 2 schemas in mongoose and typescript, where each schema has a field that references the other schema. Here's an example: const Schema1: Schema = new Schema({ fieldA: Number, fieldB: Sch ...

The process of unit testing a component to verify the presence of a specific component on the page

Presenting my straightforward custom component dubbed as NavbarComponent with the selector app-navbar. This component serves as a basic static navbar and is being displayed in app.component.html: app.component.html <app-navbar></app-navbar> &l ...

Leverage the power of TypeScript with knockout's pureComputed function

I am facing an issue with referencing the this object in a function called problem: const c = { f() { console.log("hi"); }, problem: ko.pureComputed(() => { return this.f(); }), }; [ts] The containing arrow function captures the glob ...

Angular-cli working in conjunction with an express project

I am currently working on a project that involves Express, MongoDB, and the REST API. I now want to integrate Angular into the project using angular-cli. However, I have several questions about the process. Here is the current structure of my project: htt ...