如何在Angular应用中嵌入Stripe定价表?
在Angular中嵌入Stripe可嵌入定价表
方法1:全局加载脚本 + 模板直接使用标签
- 首先在项目根目录的
index.html中添加Stripe定价表的脚本:<script async src="https://js.stripe.com/v3/pricing-table.js"></script> - 为避免Angular将未知标签识别为组件报错,需要在对应模块(如
app.module.ts)中声明允许自定义元素:import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [], bootstrap: [AppComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA] // 加入这一行 }) export class AppModule { } - 最后在组件模板(如
app.component.html)中直接插入Stripe提供的代码片段:<stripe-pricing-table pricing-table-id="xxx_xxxxxxxxxx" publishable-key="pk_test_xxxxxxxxxx" > </stripe-pricing-table>
方法2:组件内动态加载脚本(按需加载场景)
如果不想全局加载脚本,可在目标组件中动态注入:
- 组件代码示例(
app.component.ts):import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit(): void { // 检查脚本是否已存在,避免重复加载 if (!document.querySelector('script[src="https://js.stripe.com/v3/pricing-table.js"]')) { const script = document.createElement('script'); script.src = 'https://js.stripe.com/v3/pricing-table.js'; script.async = true; document.body.appendChild(script); } } } - 同样需要在模块中添加
CUSTOM_ELEMENTS_SCHEMA,模板使用方式与方法1一致。
注意事项
- 务必替换示例中的
pricing-table-id和publishable-key为你自己的真实值 - Stripe Elements确实没有对应该定价表的组件,直接使用官方自定义元素是最直接的解决方案
- 若出现样式冲突,可检查Angular全局样式与Stripe定价表样式的优先级,按需调整样式规则
内容的提问来源于stack exchange,提问作者Kuyashii
相关产品推荐
相关产品推荐

