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, but the same approach can be use for any other support payment method.
    Mount the element into the DOM.
With those technique we have access the the Stripe Element directly.
This is a more flexible approach, but also a little bit more involving
stripe-mount.component.ts
stripe-mount.component.html
1
import { Component, OnInit, ViewChild } from '@angular/core';
2
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
3
4
import { StripeService } from "ngx-stripe";
5
import {
6
StripeElements,
7
StripeCardElement,
8
StripeCardElementOptions,
9
StripeElementsOptions
10
} from '@stripe/stripe-js';
11
12
@Component({
13
selector: 'app-stirpe-mount',
14
templateUrl: '/stripe-mount.component.html'
15
})
16
export class StripeTestComponent implements OnInit {
17
elements: StripeElements;
18
card: StripeCardElement;
19
20
cardOptions: StripeCardElementOptions = {
21
style: {
22
base: {
23
iconColor: '#666EE8',
24
color: '#31325F',
25
fontWeight: '300',
26
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
27
fontSize: '18px',
28
'::placeholder': {
29
color: '#CFD7E0'
30
}
31
}
32
}
33
};
34
35
elementsOptions: StripeElementsOptions = {
36
locale: 'es'
37
};
38
39
stripeTest: FormGroup;
40
41
constructor(
42
private fb: FormBuilder,
43
private stripeService: StripeService
44
) {}
45
46
ngOnInit() {
47
this.stripeTest = this.fb.group({
48
name: ['', [Validators.required]]
49
});
50
this.stripeService.elements(this.elementsOptions)
51
.subscribe(elements => {
52
this.elements = elements;
53
// Only mount the element the first time
54
if (!this.card) {
55
this.card = this.elements.create('card', this.cardOptions);
56
this.card.mount('#card-element');
57
}
58
});
59
}
60
61
createToken() {
62
const name = this.stripeTest.get('name').value;
63
this.stripeService
64
.createToken(this.card, { name })
65
.subscribe((result) => {
66
if (result.token) {
67
// Use the token
68
console.log(result.token.id);
69
} else if (result.error) {
70
// Error creating the token
71
console.log(result.error.message);
72
}
73
});
74
}
75
}
Copied!
1
<form novalidate (ngSubmit)="createToken()" [formGroup]="stripeTest">
2
<input type="text" formControlName="name" placeholder="Jane Doe">
3
<div id="card-element" class="field"></div>
4
<button type="submit">
5
CREATE TOKEN
6
</button>
7
</form>
Copied!
Last modified 1yr ago
Copy link