ng4-paypal-button
ng4-paypal-button copied to clipboard
Sometimes paypal button div element is not rendered in time and checkout.js throws an error
I noticed that ngAfterViewCheck, probably when layout and app structure are more complex, randomly triggers checkout.js script load and button render before the paypal button div is rendered, generating a Document is ready and element #paypal-button does not exist
error.
I solved this by using a setInterval function on the constructor instead, checking every 1s if #paypal-button div is available and subsequently loading the paypal script.
constructor() {
[...]
this.intervalId = setInterval(() => {
const elementExists = !!document.getElementById('paypal-button')
if (elementExists) {
this.loadPaypalScript().then(() => {
paypal.Button.render(this.paypalConfig, '#paypal-button')
this.loading = false
})
}
}, 1000)
[...]
}
public loadPaypalScript(): Promise<any> {
clearInterval(this.intervalId) //clear interval here to stop checking for element
[...]
}
Good catch! Perhaps a cleaner solution would be to implement the elementExists
check inside of ngAfterViewChecked
, since that hook should be called whenever more parts of the template are rendered.
Try something like:
public ngAfterViewChecked(): void {
const elementExists: boolean = !!document.getElementById('paypal-button');
if(elementExists && !this.didPaypalScriptLoad) {
this.loadPaypalScript().then(() => {
paypal.Button.render(this.paypalConfig, '#paypal-button');
this.loading = false;
});
}
}
Let me know if this works for you.