I’m working on integrating payment forms from a third party, by using the Link to Javascript they provide.
when I place the code in the index.html page its works just fine, but when I move the code to the component template is not working, below is part of the code:
this is the script code to initialize the payment form:
<script>
var tokenpay = TokenPay('tokenpay123');
tokenpay.initialize({
dataElement: 'card',
errorElement: 'errorMessage',
amountElement: 'amount',
useACH: false,
//if displaying all 4 fields then useStyles=false, disableZip=false, disableCvv=false
//if displaying 3 out of 4 fields then useStyles=false, and set disableZip or disableCvv equal to true
//if displaying 2 out of 4 fields then useStyles=true, disableZip=true, disableCvv=true
useStyles: false,
disableZip: true,
disableCvv: false
});
var form = document.getElementById('paymentForm');
form.addEventListener('submit', function(event) {
event.preventDefault();
tokenpay.createToken(function(result) {
alert(result.token)
}, function(result) {
console.log("error: " + result);
});
});
</script>
<script type="text/javascript" src="http://xxx/tokenPay.js"></script>
<form id="paymentForm" action="xxx" method="post" style="margin: 10%;">
<div id="card" style="border: solid 1px lightgray; height: 100px; width: 500px; padding: 20px 10px; border-radius: 10px; margin: 10px 0px;">
</div>
<div id="errorMessage" style="margin-bottom: 10px; color: #c0392b;"></div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
when I’m using these three-part together on the index page is working fine when I’m trying to work from a component template that is not
Advertisement
Answer
Put the script tag <script type="text/javascript" src="http://xxx/tokenPay.js"></script>
inside the head tag within index.html
Then put the var tokenpay = TokenPay('tokenpay123');
etc block inside ngAfterViewInit
within the relevant component (i.e. the component hosting the form). Then it should work fine.
Note that because tokenPay
is a global variable, the TypeScript compiler will not recognise it so you will need to add:
declare const tokenPay: any
inside the .ts file of the relevant component.