Angular 5:使用第三方脚本在 <div *ngIf= "something" >中不起作用


中不起作用。

我目前正在将第三方库集成到 Angular 组件中。该组件依赖于我在构造器中加载的脚本:

constructor(private cdRef: ChangeDetectorRef) {
    this.loadAPI = new Promise(resolve => {
        this.loadScript();
        resolve(true);
    });
}
public loadScript() {
    let isFound = false;
    const scripts = document.getElementsByTagName('script');
    for (let i = 0; i < scripts.length; ++i) {
        if (
            scripts[i].getAttribute('src') != null &&
            scripts[i].getAttribute('src').includes('loader')
        ) {
            isFound = true;
        }
    }
    if (!isFound) {
        const dynamicScripts = [
            'https://some.script.js',
        ];
        for (let i = 0; i < dynamicScripts.length; i++) {
            const node = document.createElement('script');
            node.src = dynamicScripts[i];
            node.type = 'text/javascript';
            node.async = false;
            node.charset = 'utf-8';
            document.getElementsByTagName('head')[0].appendChild(node);
        }
    }
}

当我加载组件并且在标记的根目录中定义了第三方库时 - 它工作正常:

<div class="3rd-party" data-locale="something" data-template-id="id" data-businessunit-id="businessunit-id" data-style-height="240px" data-style-width="100%">
</div>

但是,如果我希望元素位于 *ngIfdiv 中,因此它仅在事件时可见,则不会显示:

<div *ngIf="isSliderOpen">
  <div class="3rd-party" data-locale="something" data-template-id="id" data-businessunit-id="businessunit-id" data-style-height="240px" data-style-width="100%">
</div>

为什么会这样?我怎样才能避免这种行为?

我能够通过在标记中使用 [hidden] 标签而不是 *ngIf 来实现这一点

正如@trichetriche指出的那样,这可能是由于div 从未被处理过。通过使用隐藏标签可以避免这种情况

最新更新