【问题标题】:How to detect ngSwitch changes in Angular page如何检测 Angular 页面中的 ngSwitch 更改
【发布时间】:2023-04-08 07:34:01
【问题描述】:

目前我正在将 Stripe 集成到 Angular 中。在我开始将 Stripe Elements 移动到 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>

【问题讨论】:

    标签: angular dom stripe-payments angular-changedetection ng-switch


    【解决方案1】:

    在模板中为卡片添加名称

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-16
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多