如何将外部 JavaScript 文件添加到 Angular 应用程序?

时间:2021-02-14 16:06:15

标签: javascript angular

所以我遵循了 Angular 教程,下载了示例应用程序并想使用我自己的 javascript。我首先尝试像往常一样使用 app.component.html 中的标签导入它,但这没有用。我试图实现的是一个按钮,它只是使用外部 javascript 将“hello”输出到控制台 onclick。

外部js文件代码:

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

使用 <button onclick="yep()"> 和脚本标签它不起作用,所以我搜索了它。有人建议在angular.json中的脚本中链接脚本文件,但是没有解决它,我链接了它但是yep()仍然未定义。

2 个答案:

答案 0 :(得分:0)

使用以下代码:

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

}

答案 1 :(得分:0)

我不会使用 Nicolar Stadler 的解决方案 - 在 Angular 中直接访问 ts 代码中的 DOM 是一个安全漏洞。

我在 angular.json 中链接了外部文件,并且它起作用了。在 angular.json 中 projects/#projectName#/architect/build/scripts 我添加了

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

(这是我的外部文件的路径)。我尝试用两种方式调用它,无论是你的:

<button  onclick="yep()">

还有更多的 Angular 方式:

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

在组件中定义 callYep() 的地方:

callYep() {yep();}

其中 yep() 是外部方法,但必须为打字稿声明:

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

并且在单击按钮时两次调用外部方法。