如何检测 Angular 页面中的 ngSwitch 变化

How to detect ngSwitch changes in Angular page

目前我正在将 Stripe 集成到 Angular。在我开始将条纹元素移动到 ngSwitchCaseng-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()

原因是 stripe 试图在 ngSwitchCase 出现之前 mount 元素。我尝试使用 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>

现在,您可以在使用 setter 呈现时收到通知。 在组件中:

 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;
    }
 }