angular - 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>
就是这样。。
我不确定我在这里还有什么其他选择。
解决方案
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.
推荐阅读
- python - windows上的python权限被拒绝
- python - 从网站上的图表中抓取数据,只有将鼠标悬停在图表上才能看到
- python - Python 的“setuptools”不包括自动生成的 SWIG Python 文件
- laravel - 如何仅保护我的控制器的特定路由?
- java - java中如何获取LinkedList的头节点?
- parsing - 在 `std::string::String` 中找不到 .next() 方法
- swift - NSTokenfield 的 ChangeToken 颜色
- .net-core - 通过环境变量向 .net 控制台应用程序添加机密的最新消息是什么
- css - 如何使用 Jest 测试样式
- java - 巨数的阶乘不溢出堆栈但也不返回结果(JAVA)