【问题标题】:Angular 5: Using 3rd party scripts doesn't work in <div *ngIf="something">Angular 5:使用 3rd 方脚本在 <div *ngIf="something"> 中不起作用
【发布时间】:2018-04-16 16:54:11
【问题描述】:

我目前正在将第 3 方库集成到 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);
        }
    }
}

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

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

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

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

为什么会这样?以及如何避免这种行为?

【问题讨论】:

  • 我不确定这是要走的路。你可能想看看 Angular 的内置延迟加载功能。

标签: javascript html angular typescript


【解决方案1】:

我可以通过在标记中使用 [hidden] 标记而不是 *ngIf 来完成此操作

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2023-04-04
    • 2022-01-18
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多