簡體   English   中英

Angular 5-加載視圖后加載腳本

[英]Angular 5 - Loading Script After View Is Loaded

我有一個舊腳本,需要在我的角度應用程序中包括它。 關於此腳本的事情是,它與特定的組件有關,並且僅在加載組件的視圖之后才需要加載它。 對於今天,我已經成功地將其包含在OnInit函數中,但是CLI有時(並非總是出於某種原因)會引發錯誤。

 import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-player-page', templateUrl: './player-page.component.html', styleUrls: ['./player-page.component.scss'] }) export class PlayerPageComponent implements OnInit { public itemId: string; constructor() {} ngOnInit() { //We loading the player srcript on after view is loaded require('assets/scripts/player/player.js'); } } 

該腳本假定UI中存在元素,並按ID搜索它們。 將其添加到頁面頂部時,它將不起作用。 實現所需行為的最佳方法是什么?

有多種解決方案。

  1. 在組件頂部聲明require const

     declare const require: any; import { Component, OnInit } from '@angular/core'; @Component({}) ... 
  2. 使用打字稿中的動態import()函數

     ngAfterViewInit() { //We loading the player script on after view is loaded import('assets/scripts/player/player.js'); } 
  3. 將庫更改為僅在從組件調用函數后才開始運行,這樣就可以將其添加到angular.json的scripts數組中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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