简体   繁体   中英

Inserting Javascript into an Angular application?

Building an application in Angular, and we want to add a fairly complex component--in a general sense, not an Angular sense--that was completely built in Javascript, originally for a separate purpose. The Javascript content currently spans several files; for the sake of simplicity, we'll say there's model.js , library1.js , and library2.js , but it's more than just those three in reality. The function render() from model.js builds the component.

I've added model.js to angular.json , but when I go to my model.html page on the Angular side, the <script> tags don't seem to work at all, whether it's:

<script>
render();
</script>

or

<script>
console.log("Hello world!");
</script>

Is there any way to force to work, or a better way to make this work in general?

If you are trying to add tag directly under a Component HTML then it is not going to work I believe.

There is no Angular2 way of adding a script tag to a template.

You can do the following in the modal.component file to dynamically add a script tag use it like this:

constructor(private elementRef:ElementRef) {};

ngAfterViewInit() {
  var s = document.createElement("script");
  s.type = "text/javascript";
  s.src = "http://somedomain.com/somescript";
  this.elementRef.nativeElement.appendChild(s);
}

See also - Adding scripts to the component

In your case, you can remove the JS file from angular.json and load it at run time like this:

private addRenderJS() {
    const s = this.doc.createElement('script');
    s.src = '/path/my-render-lib.js';
    const head = this.doc.getElementsByTagName('head')[0];

    const s1 = this.doc.createElement('script');
    s1.type = 'text/javascript';
    s1.innerHTML = `
    render();
    `;
    head.appendChild(s);
    head.appendChild(s1);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM