2016-11-01 51 views
0

目前,我正在使用Angular2和Typescript創建應用程序。添加外部JavaScript文件取決於組件名稱在Angular2中

我對應用程序(主頁,配置文件頁面,...)中的不同部分以及每個部分(home.js,profile.js)的JS文件有不同的組件。

我想知道是否有可能包含此文件取決於正在加載的組件。

我試過的其他東西是將javascript文件添加到組件的視圖中,但看起來像Angular正在剝離它。

任何意見或更好的方式來做到這一點將非常感激。

謝謝

+0

爲什麼不把「home.js」和「profile.js」中的任何內容合併到它們各自的組件中?爲什麼要把它們放在單獨的文件中? –

回答

0

最後我自己解決了它。

我所做的是在我的組件上實現AfterViewInit接口,並使用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'); 
    } 
} 

我希望這可以幫助有同樣問題的人。

相關問題