[英]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.所以我按照 Angular 教程,下载了示例应用程序并想使用我自己的 javascript。 I first tried importing it like usual with the tag in app.component.html, but that didnt work.
我首先尝试像往常一样使用 app.component.html 中的标签导入它,但这没有用。 What Im trying to achieve is a button, that just outputs "hello" to the console onclick with external javascript.
我试图实现的是一个按钮,它只是将“hello”输出到控制台 onclick 和外部 javascript。
Code of the external js file:外部js文件代码:
function yep() {
console.log("hello");
}
With <button onclick="yep()">
and the script tag it didnt work, so i searched it up.使用
<button onclick="yep()">
和它没有工作的脚本标签,所以我搜索了它。 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.有人建议在 angular.json 中的脚本中链接脚本文件,但是没有解决它,我链接了它但是 yep() 仍然未定义。
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.我不会使用 Nicolar Stadler 的解决方案 - 在 Angular 中,直接在 ts 代码中访问 DOM 是一个安全漏洞。
I linked the external file in angular.json, and it worked.我在 angular.json 中链接了外部文件,它起作用了。 In angular.json in
projects/#projectName#/architect/build/scripts
I added在
projects/#projectName#/architect/build/scripts
中的 angular.json 我添加
"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:以及更多Angular方式:
<button (click)="callYep()">
where callYep() is defined in the component:其中 callYep() 在组件中定义:
callYep() {yep();}
where yep() is the external method, but it has to be declared for the typescript:其中 yep() 是外部方法,但必须为 typescript 声明:
declare global { const yep: () => {}; }
And the external method was called both times on button click.并且在按钮单击时两次调用外部方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.