Lee Winder Lee Winder - 1 month ago 15
CSS Question

Google reCaptcha not showing in Angular 2 app

I am trying to use Google reCaptcha in an Angular 2 app. Set up as described in the documentation, the reCaptcha dialog will display if the g-recaptcha tag is in the main HTML page, but will not show if in any components (whether it's the main app component, a sub component etc.)

This reCaptcha works fine

<body>
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
</body>


But the following will not show

@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
`,
})


I can see in Chrome's developer tools that when the reCaptcha is present in the HTML, it has valid dimensions (654x78)

enter image description here

But when rendered in the component the dimensions are not valid (654x0).

enter image description here

I have a Plunker showing the issue here - https://plnkr.co/edoI5Hiydkfwiyggps3e

I have tried adding my own CSS class to the div, increasing the height but still nothing shows. I have also tried various CSS styles to try and transform the div, as well as setting the compact style.

There is no output in the console regarding any errors or any indication of what is being modified.

Any ideas what in Angular 2 might be causing the properties to go awry?

Thanks

Answer

If you want to use google-recaptcha, you have to use a directive called angular2-google-recaptcha. You can find it here with detailed instructions how to install and implement it. As to why the code that works in index.html won't work in Angular 2 component, that's because Angular 2 renders its HTML template in a totally different way. It is not only height problem as you have thought, check the difference between these two:

Comments