You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 6项目中导入JS文件?

在Angular 6中导入外部JS文件实现导航栏功能

Hey there! You’ve already taken the first step by adding your nav.js to the scripts array in your config—great start! Let’s break down the rest of the process to get that navigation bar working properly:

1. 确认配置生效并重启开发服务器

First, double-check that your angular.json (Angular 6 uses this instead of the old .angular-cli.json) has the correct path to nav.js:

"architect": {
  "build": {
    "options": {
      "scripts": [
        "src/assets/js/nav.js"
      ]
      // 其他配置项...
    }
  }
}

重要提示:修改完angular.json后,一定要重启你的Angular开发服务器(停止ng serve再重新启动),否则新的脚本配置不会生效。

2. 解决TypeScript类型报错

Since TypeScript doesn’t know about the global functions in your nav.js file, you’ll need to declare them in the component where you want to use the navigation logic. For example, if your nav.js has a function called initNav(), add this declaration at the top of your component file:

declare function initNav(): void;

Replace initNav() with the actual name of the function(s) in your nav.js file.

3. 在组件中调用JS函数

Now you can call the function from your component’s lifecycle hook—ngOnInit() is perfect here because it runs after the component’s DOM has been initialized:

import { Component, OnInit } from '@angular/core';

// 声明全局JS函数
declare function initNav(): void;

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
    // 调用导航栏初始化函数
    initNav();
  }

}

额外情况:如果你的nav.js是ES6模块化的

If you wrote nav.js as an ES6 module (using export), you don’t need to add it to the scripts array at all. Just import the function directly in your component:

// 注意路径要根据你的组件位置调整
import { initNav } from '../../assets/js/nav.js';

Then call it in ngOnInit() like before.

小提醒

  • Make sure the DOM elements your nav.js function interacts with exist in your component’s template—otherwise you’ll get "element not found" errors.
  • If nav.js depends on other libraries (like jQuery), add those libraries to the scripts array before nav.js so they load first.

内容的提问来源于stack exchange,提问作者George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:06:49