在Angular2中添加一个依赖于组件名的外部Javascript文件

Add an external Javascript file depends of Component Name in Angular2

本文关键字:组件 依赖于 外部 文件 Javascript 一个 Angular2 添加      更新时间:2023-09-26

目前我正在使用Angular2和Typescript创建一个应用程序。

我在应用程序的不同部分有不同的组件(Home, Profile page,…)和每个部分的JS文件(Home . JS, Profile . JS)。

我想知道是否有可能包含这个文件取决于正在加载的组件。

我尝试过的另一件事是将javascript文件添加到组件的视图中,但看起来Angular正在剥离它。

如果有任何建议或更好的方法,我将不胜感激。

谢谢

最后我自己解决了。

我所做的是在我的组件上实现afterviewit接口,并使用jQuery加载脚本。getScript方法。

import {Component, AfterViewInit} from "@angular/core";
@Component({
    moduleId: module.id,
    selector: 'home',
    templateUrl: '../views/home.html',
    styleUrls: ['../../public/css/home.css']
})
export class HomeComponent implements AfterViewInit {
    ngAfterViewInit(): void {
        jQuery.getScript('public/js/home.js');
    }
}

我希望这能帮助到有同样问题的人。