How to load External Javascript Libraries into Angular 4 components

断了今生、忘了曾经 提交于 2019-12-07 07:29:22

A few options that I have used:

  1. Global script using angular-cli

    "scripts": [
       "global-script.js",
       { "input": "lazy-script.js", "lazy": true },
       { "input": "pre-rename-script.js", "output": "renamed-script" },
    ]
    
  2. Require in a specific module

    import { NgModule } from '@angular/core';
    ...
    require('chart.js');
    require('../../libs/chartjs-plugin-annotation');
    ...
    
  3. Add a global script at runtime based on some condition

    if (this.usesCKEditor(permissions) && !window['CKEDITOR']) {
        const url = '//cdn.ckeditor.com/4.7.3/full/ckeditor.js';
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;
        document.body.appendChild(script);
    }
    // must check if the script has loaded before using it
    

First Approach:

Refer the scripts inside the angular-cli.json file.

"scripts": [
    "../path" 
 ];

Second Approach

You can create your own directive to load script as below

import { Directive, OnInit, Input } from '@angular/core';

@Directive({
    selector: '[appLoadScript]'
})
export class LoadScriptDirective implements OnInit{

    @Input('script') param:  any;

    ngOnInit() {
        let node = document.createElement('script');
        node.src = this.param;
        node.type = 'text/javascript';
        node.async = false;
        node.charset = 'utf-8';
        document.getElementsByTagName('head')[0].appendChild(node);
    }

}

HOW TO USE

<i appLoadScript  [script]="'https://js.squareup.com/v2/paymentform'"></i>

DEMO

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