简体   繁体   中英

Render Javascript in Angular2

I am new to angular and am trying to configure paypal. This is the javascript that I want to use.

https://developer.paypal.com/demo/checkout/#/pattern/client

When I copy paste the script body into html, nothing comes up.

I tried to put the script in the ng-onit function but I'm not really sure how to do it..

component.js

    ngOnInit = function () 
    {
    paypal.Button.render({

        ...

html

  <script src="https://www.paypalobjects.com/api/checkout.js"></script>
 div id="paypal-button-container"></div

Am I suppose to put the script reference somewhere else in component.js??

Thanks

Here is working Plunker

You can't simply import stuff (in this case PayPal API) when you include JavaScript in HTML page as script . But once you do that, browser will load that script when page is being loaded. As per documentation example, it is said that after script is loaded global paypal object will be available. To use global object which is available before or not managed by Angular, we can hack it like:

declare var paypal: any;

Then you can use it in your TypeScripts. Since this 3rd party script will do some rendering , may be it is good idea to put its initialization in ngAfterViewInit life-cycle hook.

I decided to use another approach.. (paypal in angular2 https://github.com/musale/angular2-paypal )

<form #form class="form-inline" name="_xclick" 
action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="mmusale93@gmail.com">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="item_name" value="Paypal demo charge">
<input name="item_number" type="hidden" value="0001"/>
<input type="text" class="form-control" size="30" id="paypalAmount" name="amount"/>
<input type="hidden" name="return" value="https://localhost:4200/" />
<input type="hidden" name="cancel_return" value="https://localhost:4200/" />
<input type="hidden" name="custom" value={{title}}>
<!--pass your notification URL-->
<input name="notify_url" value="YOUR NOTIFICATION URL" type="hidden"><br/>
<br/>
<input (click)="form.submit()" type="image" 
src="https://www.paypal.com/en_US/i/btn/btn_buynow_LG.gif" border="0"
            name="submit" alt="Make payments with PayPal - it's fast, free 
and secure!"/>
</form>

This made a paypal button and all it's dynamic elements easy.

By default Angular removes all the script in html except the index.html. You can either add the script in index.html or dynamically add it using Renderer2.

Somewhat similar approach can be found here: http://tphangout.com/angular-5-paypal-express-checkout/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM