![](/img/trans.png)
[英]How to add a external javascript library file to a specific component in Angular version 7
[英]How to add an external JavaScript file to an Angular app?
所以我按照 Angular 教程,下载了示例应用程序并想使用我自己的 javascript。 我首先尝试像往常一样使用 app.component.html 中的标签导入它,但这没有用。 我试图实现的是一个按钮,它只是将“hello”输出到控制台 onclick 和外部 javascript。
外部js文件代码:
function yep() {
console.log("hello");
}
使用<button onclick="yep()">
和它没有工作的脚本标签,所以我搜索了它。 有人建议在 angular.json 中的脚本中链接脚本文件,但是没有解决它,我链接了它但是 yep() 仍然未定义。
适用于以下代码:
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');
}
}
我不会使用 Nicolar Stadler 的解决方案 - 在 Angular 中,直接在 ts 代码中访问 DOM 是一个安全漏洞。
我在 angular.json 中链接了外部文件,它起作用了。 在projects/#projectName#/architect/build/scripts
中的 angular.json 我添加
"scripts": ["src/assets/external.js"]
(这是我的外部文件的路径)。 我尝试以两种方式调用它,无论是你的:
<button onclick="yep()">
以及更多Angular方式:
<button (click)="callYep()">
其中 callYep() 在组件中定义:
callYep() {yep();}
其中 yep() 是外部方法,但必须为 typescript 声明:
declare global { const yep: () => {}; }
并且在按钮单击时两次调用外部方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.