问题描述
目前,我正在将Stripe集成到Angular中。在我开始将Stripe Elements移至ngSwitchCase
和ng-container
那是我开始收到此错误的时间:
ERROR IntegrationError: The selector you specified (#card-element) applies to no DOM elements
that are currently on the page.
Make sure the element exists on the page before calling mount()
原因是,条带尝试在mount
显示之前ngSwitchCase
元素。我尝试使用ngAfterViewInit
,但似乎该函数在第一次呈现组件时执行一次,而不是在ngSwitch
更改视图时执行。
有没有一种方法可以检测组件视图中的更改?这样,我就知道在组件完全渲染之后何时mount()
使用Stripe元素。请注意,根据Angular文档,下面请注意,我使用的ng-container
不会将DOM节点添加到HTML。
<ng-container [ngSwitch]="selectedForm">
<ng-container *ngSwitchCase="'FORM_ONE'">
<form>
...
</form>
</ng-container>
<ng-container *ngSwitchCase="'FORM_TWO'">
<form>
...
</form>
</ng-container>
<ng-container *ngSwitchCase="'FORM_THREE'">
// Stripe 'card-element'
<form action="/charge" method="post" id="payment-form">
<label for="card-element">Credit or debit card</label>
<div id="card-element"></div>
<div id="card-errors" role="alert"></div>
</form>
</ng-container>
</ng-container>
解决方法
在模板中为卡添加名称
<ng-container *ngSwitchCase="'FORM_THREE'">
// Stripe 'card-element'
<form action="/charge" method="post" id="payment-form">
<label for="card-element">Credit or debit card</label>
<div #stripeCard id="card-element"></div>
<div id="card-errors" role="alert"></div>
</form>
</ng-container>
现在,使用设置器渲染时,您会收到通知。 在组件中:
card:ElementRef;
@ViewChild('stripeCard') set content(content: ElementRef) {
if(content) { // initially setter gets called with undefined
//mount it here...
//for future reference...
this.card=content;
}
}