Nicolas Stadler
Nicolas Stadler

Reputation: 121

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.

Upvotes: 1

Views: 6653

Answers (2)

Dano
Dano

Reputation: 254

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.

Upvotes: 1

Nicolas Stadler
Nicolas Stadler

Reputation: 121

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');
  }

}

Upvotes: 0

Related Questions