简体   繁体   中英

How to add an external JavaScript file to an Angular app?

So I followed the Angular tutorial, downloaded the example app and wanted to use my own javascript. I first tried importing it like usual with the tag in app.component.html, but that didnt work. What Im trying to achieve is a button, that just outputs "hello" to the console onclick with external javascript.

Code of the external js file:

function yep() {
  console.log("hello");
}

With <button onclick="yep()"> and the script tag it didnt work, so i searched it up. Someone suggested to link the script file in scripts in angular.json, but that didtn solve it, I linked it b ut yep() is still undefined.

Works with following code:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  title = 'app';
  loadScript(url) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }

  ngOnInit() {
    this.loadScript('../assets/scripts/index.js');
  }

}

I wouldn't use Nicolar Stadler's solution - in Angular accessing DOM in ts code directly is a security vulnerability.

I linked the external file in angular.json, and it worked. In angular.json in projects/#projectName#/architect/build/scripts I added

"scripts": ["src/assets/external.js"]

(that's the path to my external file). And I tried calling it in 2 ways, either yours:

<button  onclick="yep()">

And more Angular way:

<button (click)="callYep()">

where callYep() is defined in the component:

callYep() {yep();}

where yep() is the external method, but it has to be declared for the typescript:

declare global { const yep: () => {}; }

And the external method was called both times on button click.

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