Can you implement a widget that uses a <script> tag in Angular2?

我是研究僧i 提交于 2020-01-06 19:55:16

问题


We have an existing widget using <script> tags that we wrote, for third party customers to add to their site. When added, it generates all the HTML, forms, etc for the widget. We did this to avoid all the hassles of iframes.

From my understanding, Angular2 does not allow <script> tags in a template? I assume their are many widgets that work the way ours do? Is there some way to do this in Angular2? Or did we miss the mark and there is a better way entirely (iframe?) to do a similar function?

The widget itself it written in jQuery, I am not sure that it matters, but it is. I would happily re-write the widget in Angular2, but it still must "plugin" to any website.


回答1:


Angular1 would not trigger script tags from templates (unless you used jQuery as well), and Angular2 probably does about the same thing. However there is nothing stopping your from inserting the script tag with pure JS.

I have not done this in Angular2, but in Angular1 I would do something like this inside a directive.

document.createElement('script');
script.src = "/assets/game/dmloader.js";
document.getElementsByTagName('head'[0].appendChild(script);

I would assume the same works in Angular2.




回答2:


For those looking for the actual ng2 syntax (thanks for the idea - the logic was correct)

import {Component, ElementRef, Directive} from 'angular2/core';

@Directive({ selector: '[mywidget]' })

export class MyDirective {
    constructor(private el: ElementRef) {
       let tag = document.createElement('script');
       tag.id = "scriptId";
       tag.setAttribute("myattr", "myvalue");
       tag.src = "https://cdn.acmeproject.org"
       this.el.nativeElement.appendChild(tag); 
     }
}


来源:https://stackoverflow.com/questions/34950194/can-you-implement-a-widget-that-uses-a-script-tag-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!