1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.