簡體   English   中英

如何將外部 JavaScript 文件添加到 Angular 應用程序?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM