1

I'm building an Angular 5 app and I'm trying to add a widget to one of the components.

I try adding it like the answer in this question, but it fails to load some times, I don't know why.

The widget is loaded with this script:

<script src="https://example.com/widget/js/widgetLoader.js"
        type="text/javascript"
        charset="utf-8" 
        data-id="xxxxx" 
        data-target="WidgetPlaceHolder"
        data-displaymeta="off"
        data-css="https://example.com/widget/css/temp/widget.css"
        data-type="widget-type"
        data-lv="en"
        data-apikey="xxx-xxx">
</script>

And I'm adding it to my component like this:

public loadScript() {
    let widgetScripts = 'https://example.com/widget/js/widgetLoader.js';
    let node = document.createElement('script');
    node.src = widgetScripts ;
    node.type = 'text/javascript';
    node.async = false;
    node.charset = 'utf-8';
    node.setAttribute('data-id', this.information.id);
    node.setAttribute('data-target', 'WidgetPlaceHolder');
    node.setAttribute('data-displaymeta', 'off');
    node.setAttribute('data-css', 'https://example.com/widget/css/temp/widget.css');
    node.setAttribute('data-type', 'widget-type');
    node.setAttribute('data-lv', 'en');
    node.setAttribute('data-apikey', 'xxx-xxx');
    document.getElementsByTagName('head')[0].appendChild(node);
}

Then:

loadWidget: Promise<any>;

ngOnInit() {
    this.loadWidget = new Promise((resolve) => {
        this.loadScript();
        resolve(true);
    });
}

The question is, is there a proper way for adding scripts in Angular? Is there an Angular API or library to do this?

David Prieto
  • 2,239
  • 4
  • 32
  • 51

1 Answers1

0

If you've build your project using Angular CLI the in your angular.json file in the root of the project there is a script property where you have to add the reference to the script.

    "assets": [
      "src/favicon.ico",
      "src/assets"
    ],
    "styles": [
      "src/styles.css"
    ],
    "scripts": [ADD IT HERE]
  },
Mac_W
  • 2,927
  • 6
  • 17
  • 30
  • Yes but the parameters are dynamic, like "data-id", how do I pass those to the script and reload every time the component initializes? – David Prieto Jul 05 '18 at 08:19