首页 > 解决方案 > DOM 元素的 ID 已设置但无法安装

问题描述

我想实现一个组件,它在给定@Input参数的情况下动态设置 DOM 树中特定元素的 ID。

使用客户端库,特别是 Stripe 客户端(stripe.js),我想在该元素上安装更复杂的组件,如下所示:

@ViewChild('elementRef', {read: ElementRef}) elementRef: ElementRef;

// ..

get elementId() {
  return this.type ? this.type + '-element' : null;
}

ngOnInit() {
  this.elementRef.nativeElement.id = this.elementId;
  this._cd.detectChanges();
}

ngAfterViewInit() {
  this._element = this._stripeClientService.elements.create(this.type, this.options);

  setTimeout(() => {
    console.log(document.getElementById(this.elementId));
    this._element.mount(this.elementId);
  }, 100);


  this._element.on('change', (event) => {
    const displayError = document.getElementById('errors');
    if (event.error) {
      displayError.textContent = event.error.message;
      this.canSubmit = false;
    } else {
      displayError.textContent = '';
      this.canSubmit = true;
    }
  });
}

问题:即使我使用setTimout()(不应该是必要的恕我直言),调用detectChanges()尝试初始化组件ngAfterViewInit(),我仍然得到这个:

ERROR IntegrationError: The selector you specified (iban-element) applies to no DOM elements that are currently on the page. Make sure the element exists on the page before calling mount().
    at new t (https://js.stripe.com/v3/:1:11502)
    at t.<anonymous> (https://js.stripe.com/v3/:1:97045)
    at t.mount (https://js.stripe.com/v3/:1:25699)

**然而*,我也确实看到了这个,来自console.log(document.getElementById(this.elementId));控制台:

<div _ng-content-c29 id="card-element"></div>

就是这样。。

我不确定我在这里还有什么其他选择。

标签: angulartypescriptstripe-payments

解决方案


So, I don't know why it did not work with a string. I was able to do it before when I had separate components and put in card or iban separately. However, this does not seem to work in a dynamic environment.

But what does work is this apparently:

this._element.mount(this.elementRef.nativeElement);

I just passed in the nativeElement and apparently the API can work with that too.


推荐阅读