Search code examples
angularnumberslistenerelement

How to add an input listener on Stripe Elements (Angular)


My objective is to bind my component variable numberOfCreditCard with the input card number. Template :

<div class="example example2" id="example-2">
    <form>
        <div class="row">
            <div class="field">
                <div id="example2-card-number" class="input empty" #cardNumber></div>
                <label for="example2-card-number" data- 
                  tid="elements_examples.form.card_number_label">Card number</label>
                <div class="baseline"></div>
            </div>
        </div>
        .
        .
        .
    </form>
</div>

I can't just use ngModel because it wont work on a div element, So I used my stripe elements :

const stripe = Stripe(environment.stripeAPIpublicKey);
const elements = stripe.elements();

let cardNumber2 = elements.create('cardNumber', {
    style: elementStyles,
    classes: elementClasses
});

According to the official documentation https://stripe.com/docs/js/element/events/on_change?type=cardElement, that's what I did :

cardNumber2.on('changes', function(event) {
   console.log("new value in card number");
   // this.numberOfCreditCard = the value returned
});

The thing is that "new value in card number" is not displayed in the console each time a new key is pressed, while that's what I want, in order to take the event and give it to my variable.

My objective is to get the entered values for the card number in order to display the numbers on a beautiful credit card like this : https://codepen.io/mycnlz/pen/reLOZV


Solution

  • The stripe elements are isolated in an iFrame for PCI compliance. The action you are trying to take (as innocent as it is for your described intended purpose) is specifically prevented so you are not able to "grab" the credit card numbers from your user.