【问题标题】:Angular , how to apply an attribute directive to an element in index.htmlAngular,如何将属性指令应用于 index.html 中的元素
【发布时间】:2019-05-15 21:04:06
【问题描述】:

我在 index.html 中有一些异步 javascript 库的脚本标签,我想通过将 type 属性从“text/plain”更改为“text/javascript”来应用它们一个属性指令来控制它们的“激活”。用户提供 cookie 同意。该指令似乎永远不会被角度到达,也许是因为它在角度区域之外,实际上在构造函数和订阅函数的回调中的日志永远不会在控制台中打印并且指令变得无用。

@Directive({
  selector: '[appLoadOnConsent]'
})
export class LoadOnConsentDirective implements OnInit, OnDestroy {
  private statusChangeSubscription: Subscription;
  constructor(
    private ccService: NgcCookieConsentService,
    el: ElementRef
  ) {
    // never printed
    console.log(el);
  }

  ngOnInit() {

    this.statusChangeSubscription = this.ccService.statusChange$.subscribe(
      (event: NgcStatusChangeEvent) => {
        // never printed
        console.log('cookie status change', event);
      });
  }

  ngOnDestroy() {
    this.statusChangeSubscription.unsubscribe();
  }
}

在 index.html 中

<head>
  ....
  // library 1
  <script type="text/plain" appLoadOnConsent async defer src="https://external.library1.js"></script>
  // library 2
  <script type="text/plain" appLoadOnConsent async defer src="https://external.library2.js"></script>
</head>
....

我怎样才能达到我的目标?有没有更好的方法来解决我的问题?

【问题讨论】:

    标签: angular directive


    【解决方案1】:

    您可以尝试在加载包之前等待同意。

    假设您有一个同意处理程序

    handleConsent(consentGiven: boolean): void {
        if (consentGiven) {
            console.log('consent was given');
        }
    }
    

    现在我不知道这是否可行,但我会试试这个。做一个dynamic import

    所以它可能看起来像这样:

    handleConsent(consentGiven: boolean): void {
        if (consentGiven) {
            import('https://external.library1.js')
            .then((module) => {
                module.default();
                module.doStuff();
            });
        }
    }
    

    这行得通吗?

    【讨论】:

      【解决方案2】:

      看起来 Angular 不会让你处理任何脚本。请查看here 其他人如何动态加载脚本。

      【讨论】:

      • 我知道您链接的帖子中的技术,可能我会实施这些技术,但仍然存在疑问,对 index.html 中的元素应用指令不起作用,因为我不在角度区域或因为 Angular 会阻止对标记脚本的任何操作?
      • 我认为 Angular 会阻止模板中的脚本标签。我在 中的 stackblitz 上进行了尝试。除了
      • 我试图将该指令应用于 index.html 中的 div 元素但不起作用,如果您将该 div 放入 app.component.html 中,它会起作用,所以我认为一切都是AppComponent 之外在角度区域之外,无法应用它们
      • 您是否尝试在 AppModule 的 bootstrap: [] 元素中声明您的指令?
      • 你是对的,但我解决了在应用程序组件中创建一个组件,该组件管理脚本标签,在 cookie 同意时动态添加它们
      猜你喜欢
      • 2020-02-21
      • 2020-07-24
      • 2017-12-21
      • 2014-03-08
      • 1970-01-01
      • 2016-10-26
      • 2013-10-17
      • 2017-09-20
      • 2014-12-17
      相关资源
      最近更新 更多