richnologies / ngx-stripe

Angular 6+ wrapper for StripeJS
MIT License
219 stars 77 forks source link

Access the StripeCardComponent in ng-template #139

Closed yehiasalam closed 2 years ago

yehiasalam commented 3 years ago

Hello,

I'm trying to create a payment method using the stripe service as below:

@ViewChild(StripeCardComponent) card: StripeCardComponent;
...
this.stripeService.createPaymentMethod({
        type: 'card',
        card: this.card.element,
        billing_details: {
                  name: name
        }
}).subscribe((result) => {
...
});

The problem is that the stripe component is placed in an ng-template, so the reference to card component is always undefined this.card.element. I know this is an angular issue since the ng-template element is not added in the component initiation and is later added dynamically. But still how to refer to this.card without using the ViewChild decorator.

<ng-template>
     <ngx-stripe-card [options]="cardOptions" [elementsOptions]="elementsOptions"></ngx-stripe-card>
</ng-template>

I'm using angular 10 with the correpsonding version of the stripe component.

Thanks for the component.

richnologies commented 3 years ago

Hi @yehiasalam, happy to help. The info you provide is bit light, so I'm not sure if I'm replicating the scenario correctly.

I've created a Stackblitz project for this issue so we can work this one out ;)

Here is the source code: https://stackblitz.com/edit/ngx-stripe-issue-139?devtoolsheight=33&file=src/app/app.component.html

For some reason, the embedded view is not working for this example, so you will need to open the dev server in a separate window: https://ngx-stripe-issue-139.stackblitz.io/

As I've said, details are a bit light, but I've used the setTimeout to simulate the added dynamically the component later, so please, feel to fork this Stackblitz and modify it as you see fit, this way it would be easier for me to understand the problem

Kind Regards

R