Manually Mount your Element
In some scenarios you may want to fully control the style, the loading flow or simply the provided Element Components don't suit well for your application.
In those cases you manually mount the Stripe Element on any DOM element. In the example bellow, we are mounting a Card Element into the div with id card-element. We need to do 3 things the Card Component usually do for us:
- Fetch the Elements Object
- Create the Stripe Element. In this example, a card element is used, but the same approach can be applied to any other supported payment method.
- Mount the element into the DOM
By doing the steps above, we gain direct access to the Stripe Element.
This is a more flexible approach, but also a little bit more involving
Usage
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { StripeService } from "ngx-stripe";
import {
StripeElements,
StripeCardElement,
StripeCardElementOptions,
StripeElementsOptions
} from '@stripe/stripe-js';
@Component({
selector: 'ngstr-stirpe-mount',
templateUrl: '/stripe-mount.component.html'
})
export class StripeTestComponent implements OnInit {
elements: StripeElements;
card: StripeCardElement;
cardOptions: StripeCardElementOptions = {
style: {
base: {
iconColor: '#666EE8',
color: '#31325F',
fontWeight: '300',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSize: '18px',
'::placeholder': {
color: '#CFD7E0'
}
}
}
};
elementsOptions: StripeElementsOptions = {
locale: 'es'
};
stripeTest: FormGroup;
constructor(
private fb: FormBuilder,
private stripeService: StripeService
) {}
ngOnInit() {
this.stripeTest = this.fb.group({
name: ['', [Validators.required]]
});
this.stripeService.elements(this.elementsOptions)
.subscribe(elements => {
this.elements = elements;
// Only mount the element the first time
if (!this.card) {
this.card = this.elements.create('card', this.cardOptions);
this.card.mount('#card-element');
}
});
}
createToken() {
const name = this.stripeTest.get('name').value;
this.stripeService
.createToken(this.card, { name })
.subscribe((result) => {
if (result.token) {
// Use the token
console.log(result.token.id);
} else if (result.error) {
// Error creating the token
console.log(result.error.message);
}
});
}
}